Android-startService后台运行
Posted 原创Android 努力学习 专一安卓 持之以恒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android-startService后台运行相关的知识,希望对你有一定的参考价值。
什么时候使用startService?
答:APP在后台长时间运行并执行业务的时候,可以用服务,主要是看服务的特点(在后台长时间运行);
Service相关代码:
package liudeli.service1.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService4 extends Service { private final static String TAG = MyService4.class.getSimpleName(); private final static int RUN = 1; private final static int NOT_RUN = 0; private int runState; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { runState = RUN; new Thread(new BackgroundRun()).start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); runState = NOT_RUN; } /** * startService 不能直接执行耗时操作,需要通过异步去执行耗时操作,Service只负责长时间到在后台服务运行 * Service是开启主线程的,Service与Activity很类似,都是开启运行主线程的 */ class BackgroundRun implements Runnable { @Override public void run() { while (runState == RUN) { Log.d(TAG, "Background Run ......"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
MainActivity4相关代码:
public void startService(View view) { startService(new Intent(this, MyService4.class)); } public void stopService(View view) { stopService(new Intent(this, MyService4.class)); }
Log日志,Service去启动线程一秒执行一次:
12-06 22:54:07.489 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:08.490 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:09.495 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:10.500 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:11.507 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:12.508 8204-8301/liudeli.service1 D/MyService4: Background Run ......
12-06 22:54:13.509 8204-8301/liudeli.service1 D/MyService4: Background Run ......
以上是关于Android-startService后台运行的主要内容,如果未能解决你的问题,请参考以下文章