当应用程序出现问题而不能手动重启应用时,就需要远程控制程序的重启。例如可以通过推送,应用收到推送,调用restartAPP()方法,重启App。
* 重启整个APP
* @param context
/
public static void restartAPP(Context context) {
/开启一个新的服务,用来重启本APP/
Intent intent = new Intent(context, RestartService.class);
intent.putExtra("packageName", context.getPackageName());
context.startService(intent);
/杀死整个进程/
android.os.Process.killProcess(android.os.Process.myPid());
}
/**
* Created by wangfengkai on 2017/6/22.
*/
public class RestartService 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) {
packageName = intent.getStringExtra("packageName");
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
startActivity(LaunchIntent);
RestartService.this.stopSelf();
}
}, stopDelayed);
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在AndroidManifest.xml中注册Service
<service android:name=".service.RestartService" />