以编程方式重新启动设备时不会触发用于关闭的BroadcastReceiver

时间:2018-09-19 11:08:25

标签: android android-broadcastreceiver

我必须在特定时间重新启动设备。为此,我正在使用以下代码

private void rebootAfterSomeTime() {
    h = new Handler(Looper.getMainLooper());
    r = new Runnable() {

        public void run() {

            //current time
            Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int min = c.get(Calendar.MINUTE);
            int sec = c.get(Calendar.SECOND);
            String currenttime = String.valueOf(hour) + " : " + String.valueOf(min) + " : " + String.valueOf(sec);
            Log.d("Gajanand", "run: "+currenttime);

            //comparing current time with 12:00pm
            if (currenttime.equals("23 : 59 : 59")) {

                //reboot the device
                rebootDevice();

            }

            h.postDelayed(this, delayMillis);

        }
    };

    h.post(r);
}

我正在通过两种方法重启设备,一种方法是使用powerManager,另一种方法是使用SU ..

     private void systemAppsrebootOnly() {

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        pm.reboot(null);

    }

  public static void rebootDevice() {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("reboot \n");
        } catch (Throwable t) {

            t.printStackTrace();
        }
    }

在两种情况下都可以正常重启设备,但在两种情况下都不会触发BroadcastReceiver。但是当我通过长按电源按钮手动重新启动设备并重新启动该时间BroadcastReceiver触发时。这是我的ShutdownReceiver

    public class ShutdownReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        /*if(intent.getAction().equalsIgnoreCase("android.intent.action.BOOT_COMPLETED"))
        {
            Toast.makeText(context, "boot_completed", Toast.LENGTH_SHORT).show();
        }
        else*/
//            Toast.makeText(context, ""+intent.getAction(), Toast.LENGTH_SHORT).show();

        Log.e("kishan", "onReceive:mPowerReceiver powerofffffffffff");
        ManvishPrefConstants.SHUTDOWN_TRIGGERED.write(true);
        ManvishPrefConstants.SHUTDOWN_DATE_TIME.write(CommanUtils.formatDate(System.currentTimeMillis()));
    }
}

清单文件的小部分。我已添加了所有必要的权限。

<receiver android:name=".Activities.ShutdownReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_SHUTDOWN"/>
            <action android:name="android.intent.action.ACTION_REBOOT"/>
            <action android:name="android.intent.action.QUICKBOOT_POWEROFF"/>
        </intent-filter>
    </receiver>

有什么帮助吗?

0 个答案:

没有答案