onReceive() method not opening application while d

2019-09-06 11:51发布

问题:

Hi friends i have a problem... Actually i use this code to open my application in certain time..the app is working fine but when the device is in sleep mode not working..??

public class MyBroadCastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context ctx, Intent intent) {
        Intent intent = new Intent(ctx, ActivityMain.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        ctx.startActivity(intent);
    }

}

ActivityMain.java

intent = new Intent(getBaseContext(), MyBroadCastReceiver.class);

        pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), REQ_CODE, intent, 0);

        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (60 * 1000), pendingIntent);

In device sleep mode not working, BroadCastReceiver Calss unable to open the MainActivity class.

I have given permission in menifest

<uses-permission android:name="android.permission.WAKE_LOCK"/>

Any Help please.

回答1:

The wake lock of your broadcast receiver is only guaranteed to keep the phone awake for the duration of the onReceive method. If you need to do work beyond that method, you need to aquire/manage another wake lock.

A Commonsware library exists for this purpose. Have a look at: https://github.com/commonsguy/cwac-wakeful/blob/master/README.markdown