Android(安卓)activity与service中的子线程 (入门级)
16lz
2021-01-25
1.首先 android 一个程序中 的activity 都是一个线程,service和activity也是一个线程
2.在activity 中启动一个子线程,当前activity finish destroy掉 子线也会运行的。
3.在service里的线程 与activity很类似 service即使停止了 线程也在运行(要先停止服务 再把最近使用的进程杀掉 线程会停止 ,如果直接杀掉进程 android会再次自动启动这个service的 此时即使再停止service服务 线程也会一直运行了除非关机)
activity 中启动一个子线程
public class SecondActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_lout);System.out.println("当前线程 执行了====SecondActivity====="+Thread.currentThread().getId()); new Thread(new Runnable() { @Overridepublic void run() { while(true){ System.out.println("当前线程 执行了==22222=="+Thread.currentThread().getId()); try {Thread.sleep(2000);} catch (InterruptedException e) { e.printStackTrace();} } }}).start(); } @Overrideprotected void onDestroy() { System.out.println("当前线程 执行了======结束====="+Thread.currentThread().getId()); super.onDestroy();} }activity finish 子线程依旧可以运行,即使程序退出了子线程也在运行 (除非在任务管理器里 把最近使用的进程杀掉)
service 中启动一个子线程
public class TestService extends Service{ @Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubSystem.out.println("当前线程 执行了====TestService0000====="+Thread.currentThread().getId()); new Thread(new Runnable() { @Overridepublic void run() { while(true){ System.out.println("当前线程 执行了==22222=="+Thread.currentThread().getId()); try {Thread.sleep(2000);} catch (InterruptedException e) { e.printStackTrace();} } }}).start();return super.onStartCommand(intent, flags, startId); } @Overridepublic void onDestroy() {System.out.println("当前线程 执行了=====TestService=结束====="+Thread.currentThread().getId()); super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;} }
以上3条是在 android 4.4.2测试的情况,其他版本没有试过。如有不对的地方请批评指正!
请注意子线程的生命周期 不要activity结束了 子线程才处理完 返回结果给UI就会有问题,也可以为耗时或者需要长时间运行的情况提供一点思路
更多相关文章
- 一款霸榜 GitHub 的开源 Linux 资源监视器!
- Android(安卓)应用程序(进程)生命周期
- Android(安卓)消息机制——你真的了解Handler?
- AsyncTask的使用及源码分析
- Android(安卓)双缓冲技术
- Android消息机制及HandlerThread、Handler内存泄漏问题
- 换一种方式理解 Android协程
- android之Handler整理
- Handler原理