自杀式服务重启app完整代码
/**
* 此工具类用来重启APP,只是单纯的重启,不做任何处理。
* Created by 13itch on 2016/8/5.
*/
public class RestartAPPTool {
/**
* 重启整个APP
* @param context
* @param Delayed 延迟多少毫秒
*/
public static void restartAPP(Context context,long Delayed){
/**开启一个新的服务,用来重启本APP*/
Intent intent1=new Intent(context,killSelfService.class);
intent1.putExtra("PackageName",context.getPackageName());
intent1.putExtra("Delayed",Delayed);
context.startService(intent1);
/**杀死整个进程**/
android.os.Process.killProcess(android.os.Process.myPid());
}
/***重启整个APP*/
public static void restartAPP(Context context){
restartAPP(context,2000);
}
}
/***
* 该服务只用来让APP重启,生命周期也仅仅是只是重启APP。重启完即自我杀死
*/
public class killSelfService extends Service {
/**关闭应用后多久重新启动*/
private static long stopDelayed=2000;
private Handler handler;
private String PackageName;
public killSelfService() {
handler=new Handler();
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
stopDelayed=intent.getLongExtra("Delayed",2000);
PackageName=intent.getStringExtra("PackageName");
handler.postDelayed(()->{
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(PackageName);
startActivity(LaunchIntent);
killSelfService.this.stopSelf();
},stopDelayed);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
最后别忘了,在AndroidManifest.xml文件中去注册Service哦
<service
android:name=".restart_app.killSelfService"
/>