君不见长松卧壑困风霜,时来屹立扶明堂。这篇文章主要讲述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去启动线程一秒执行一次:
【Android-startService后台运行】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限制只能在主线程中进行UI访问的实现原理
- Android 蓝牙
- 安卓壁纸下载|安卓壁纸app下载
- 关于win10安卓真机调试无法找到设备的问题
- Java - 33 Java Applet基础
- 安卓-APP瘦身优化
- jQuery/CSS3实现Android Dock效果
- 使用 mklink把apple 备份文件从c盘转移到D盘
- android中Zing二维码扫描,二维码生成