字形分析网站/百度推广培训
后台运行的子线程放在服务中,使得子线程更加健壮!!及时主线程Activity退出,子线程在服务中依然很滋润。
Back掉Activity之后,主线程终止,子线程依然在进行,但是此时的子线程在Activity中启动的,Activity销毁后, 此时的子线程是属于空进程,隶属于Android第5进程等级,最不稳定,在内存不够用的情况下随时可能被杀死(在android 2.X时代会有这种现象,经测试4.x之后不会被轻易杀死);此时如果把子线程放到service服务中则会健壮许多, 进程等级提升到第三级service Process.
foreground process visible progress service progress background process empty progress
把子线程放在服务中的代码如下:
package com.example.sj.demo161;import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;//子线程在主线程over后是可以继续在后台运行的
//那么我们想要实现一个后台运行效果,只要启动一个子线程就可以了
//但是,由于android的进程等级机制,导致我们的后台子线程运行,会非常非常的不稳定
//尤其是在一些老机型,或者特殊机型,或者当手机的内存比较吃紧的时候,就会把后台子线程杀掉
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void go1(View view) {Intent intent=new Intent(this,MyService.class);startService(intent);}public void go2(View view) {}public void go3(View view) {}@Overrideprotected void onDestroy() {super.onDestroy();}
}
服务中
package com.example.sj.demo161;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;//Service:服务 四大组件之二
//主要是维持后台运行程序的稳定性
//看不到,后台偷偷运行
//把握住使用原则:只要是后台运行的子线程,那么我们就放在服务中启动,那么它就会非常稳定!
public class MyService extends Service {public MyService() {}//当服务器启动时执行的方法@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {
// this.startForeground();System.out.println("执行到我啦!");new Thread(){int count=0;@Overridepublic void run() {super.run();while (true){SystemClock.sleep(2000);System.out.println("我还活着 "+count);count++;}}}.start();return super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}
}