为什么AlarmManager不起作用?

时间:2018-03-13 18:13:30

标签: android broadcastreceiver alarmmanager

这是MainActivity的onCreate()方法中的代码:

Intent intent = new Intent(this, BatteryBroadcast.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 001,  intent, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, 1000, pendingIntent);

这是BatteryBroadcast类

public class BatteryBroadcast extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryIntent = context.registerReceiver(null, intentFilter);
        Log.i("B-TAG", batteryIntent.getStringExtra(BatteryManager.EXTRA_LEVEL));
    }
}

但是BatteryBroadcast课程没有工作,为什么?

1 个答案:

答案 0 :(得分:0)

您需要在清单上添加接收器:

<receiver
android:name"package.BatteryBroadcast"
android:enabled="true">
   <intent-filter>
       <action android:name="unique_name"/>
   </intent-filter>
</receiver>
  

并称之为:

Intent intent = new Intent();
intent.setAction("unique_name");
sendBroadcast(intent)