使用AlarmManager设置报警后未调用广播接收器

时间:2017-08-19 11:27:29

标签: android broadcastreceiver alarmmanager android-broadcastreceiver

这是我的ScreenStateReceiver(一个BroadcastReceiver),它会在屏幕关闭时以及每当屏幕重新上线时接收广播。

public class ScreenStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
        Log.e("ScreenStateReceiver", "Screen Intent Action On " + intent.getAction());
        else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            Log.e("ScreenStateReceiver", "Screen Intent Action Off" + intent.getAction());
            setAlarm(context);
        }
    }

    private void setAlarm(Context context){

        Intent in  = new Intent(context, AlarmReciever.class);
        in.setAction("screen_off");
        PendingIntent sender =  PendingIntent.getBroadcast(context.getApplicationContext(), 161, in, PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager)context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
            am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + 30 * 1000L, sender);
        else
            am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() +  60 * 1000L, sender);
    }
}

现在我的AlarmManager闹钟接收器是:

public class AlarmReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("AlarmReciever", "Alarm goes off");
    }
}

现在我在MainActivity中注册了两个接收器,如下所示:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ScreenStateReceiver screenStateReceiver = new ScreenStateReceiver();
        IntentFilter in = new IntentFilter();
        in.addAction(Intent.ACTION_SCREEN_ON);
        in.addAction(Intent.ACTION_SCREEN_OFF);

        this.registerReceiver(screenStateReceiver, in);

        AlarmReciever alarmReciever = new AlarmReciever();
        in = new IntentFilter();
        in.addAction("screen_off");

        this.registerReceiver(alarmReciever, in);
    }
}

现在我很难在AlarmReceiver中打印日志,但是永远不会打印出来,当屏幕熄灭时,AlarmReceiver永远不会被调用。有人可以帮帮我吗?

0 个答案:

没有答案