杀进程代码:
kotlin
// 1. 结束同一个任务栈下的所有Activity
finishAffinity()
// 2. 退出虚拟机,内部调用System.exit(0)
exitProcess(0)
或:
kotlin
// 1. 结束同一个任务栈下的所有Activity
finishAffinity()
// 2. 杀进程,内部调用:sendSignal(pid, SIGNAL_KILL)
android.os.Process.killProcess(android.os.Process.myPid())
注意:如果有启动Service,则同时还要先结束所有Service,再执行杀进程。
两种方式皆可实现退出应用并杀掉进程。
杀掉进程后,可手动再打开应用。有时候,我们希望杀掉进程后自动重启,这样不需要手动打开,如何实现呢?
有时候发现杀进程的代码并没有把进程杀死,这是因为你的进程中还有其它Activity或Service存活,则系统会认为你的应用不应该被杀死,所以当你杀进程后,系统又会再次创建新进程,并启动之前没有关闭的Activity或Service。所以,利用这一规则,我们可以使用一个存活的Service来达到自动重启的效果,示例如下:
kotlin
class RestartAppService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val isGeneralStart = intent?.getBooleanExtra("GeneralStart", false) ?: false
Log.i("RestartAppService", "isGeneralStart=$isGeneralStart")
if (!isGeneralStart) {
applicationContext.startActivity(Intent(applicationContext, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
}
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent): IBinder? = null
}
应用一启动,我们就启动这个Service:
kotlin
startService(Intent(this, RestartAppService::class.java).apply {
putExtra("GeneralStart", true)
})
当需要重启时,就杀进程就行:
kotlin
finishAffinity()
exitProcess(0)
杀进程时,因为有RestartAppService服务还在运行,我们没有手动停止这个服务,则系统认为异常的杀了进程,所以杀掉进程后,系统又会自动创建进程,并自动启动RestartAppService,由于onStartCommand的默认返回值是START_STICKY,在系统重启RestartAppService时,它不会重传之前intent中的数据,所以此时的isGeneralStart 为false,然后就可以执行启动App的代码了。加入isGeneralStart是为了预防正常启动时会导致MainActivity又多启动了一次。
但是也需要注意,从Android 10开始,系统不允许在Service中启动Activity。
更简单的做法是,先结束所有Activity和Service,然后再启动主Activity,然后杀进程,如下:
kotlin
finishAffinity()
startActivity(Intent(this, MainActivity::class.java))
exitProcess(0)
由于在杀进程之前我们启动了一个MainActivity,所以杀掉进程后,系统会帮我们自动启动这个被异常结束的MainActivity。这个方法相比使用Service更简单,而且在Android 10以上运行也正常。