android使用服务重启app

新建一个服务类killSelfService.java


public class killSelfService extends Service {
    private static  long stopDelayed=1000;
    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(new Runnable() {
            @Override
            public void run() {
                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;
    }

}

再建一个工具类

public class RestartAPPUtil {
    public static void restartAPP(Context context, long Delayed){

        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());
    }
    public static void restartAPP(Context context){
        restartAPP(context,1000);
    }
}
发布了42 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39361915/article/details/105239891
今日推荐