1.执行ADB命令 adb shell am broadcast -a android.intent.action.REBOOT
2.使用PowerManager
import android.content.Context;
import android.os.PowerManager;

public class RebootDevice {
    public static void reboot(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        powerManager.reboot(null);
    }
}

需要增加权限:<uses-permission android:name="android.permission.REBOOT" />
3. 应用程序自动重启
有时,我们希望在应用程序崩溃或发生意外关闭时自动重启应用程序。可以使用Thread.UncaughtExceptionHandler来实现这一功能。

import android.app.Application;
import android.content.Intent;

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
    }

    private class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            // 重启应用程序
            Intent intent = getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(getBaseContext().getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            System.exit(0);
        }
    }
}

以上代码将在应用程序崩溃时自动重启应用程序。

posted on 2025-02-25 10:21  邢帅杰  阅读(3)  评论(0编辑  收藏  举报