准备工具类
import android.content.Context;
import android.content.Intent;
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());
System.exit(0);
}
/***重启整个APP*/
public static void restartAPP(Context context){
restartAPP(context,2000);
}
}
准备Service
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import com.king.armytv.MainActivity;
public class killSelfService extends Service {
/**
* 关闭应用后多久重新启动
*/
private static long stopDelayed = 50;
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", 50);
Log.i("killSelfService", "stopDelayed:" + stopDelayed);
PackageName = intent.getStringExtra("PackageName");
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent LaunchIntent = new Intent(killSelfService.this, MainActivity.class);
LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(LaunchIntent);
Log.i("killSelfService", "启动app");
killSelfService.this.stopSelf();
}
}, stopDelayed);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
3 需要权限(华为手机测试需要这两个权限,少了启动不了)
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
4 AndroidManifest.xml 注册Service
<service
android:process=":restart"
android:name=".util.killSelfService" />文章来源:https://www.toymoban.com/news/detail-568140.html
5 调用 RestartAPPTool.restartAPP(this);文章来源地址https://www.toymoban.com/news/detail-568140.html
到了这里,关于android 实现APP重启,华为亲测的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!