Android App退出检测
app的退出检测是很难的,但是获取app“要退出”的状态就容易多了,退出的瞬间并不是真的退出了,ActivityManager要销毁activity,也需要一些时间和资源的。
先见下面的运行效果:
gif做的比价粗啊,
两个activity的界面就不介绍了,主要是在APP启动的时候开启一个服务,application代码如下:
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Intent intent=new Intent(this,CheckExitService.class); getApplicationContext().startService(intent); } }
service的代码如下:
public class CheckExitService extends Service { private String packageName = "test.minwenping.com.appexitdemo"; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); Toast.makeText(CheckExitService.this, "App要退出了", Toast.LENGTH_SHORT).show(); } //service异常停止的回调 @Override public int onStartCommand(Intent intent, int flags, int startId) { ActivityManager activtyManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activtyManager.getRunningAppProcesses(); for (int i = 0; i < runningAppProcesses.size(); i++) { if (packageName.equals(runningAppProcesses.get(i).processName)) { Toast.makeText(this, "app还在运行中", Toast.LENGTH_LONG).show(); } } return START_NOT_STICKY; } @Override public void onCreate() { super.onCreate(); Toast.makeText(CheckExitService.this, "App检测服务开启了", Toast.LENGTH_SHORT).show(); } }
还有尝试了守护线程,UI就只有一个线程,想从这方面下手,但是都失败了