为什么服务在BOOT_COMPLETED上启动而在BATTERY_LOW上没有?

时间:2013-07-18 10:06:48

标签: android service broadcastreceiver android-notifications bootcompleted

为什么我的服务在BOOT_COMPLETED上启动但在BATTERY_LOW上没有?代码:

MyScheduleReceiver.java

public class MyScheduleReceiver extends BroadcastReceiver {


    // Restart service every 30 min
    private static final long REPEAT_TIME = 30*1000*4;//1800000 ;

    @Override
    public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, service.class);
context.startService(service);
}}

service.java

public class service extends Service {

    NotificationManager mNotificationManager;
      @Override public IBinder onBind(Intent intent) {
        // Not used
        return null;
      }

      @Override public void onCreate() {
        super.onCreate();
  mNotificationManager= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
checkPref();
}
@Override
      public void onDestroy() {
        super.onDestroy();

      }

private void checkPref(){ 
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                service.this);
                notificationBuilder.setContentTitle("Title");
                notificationBuilder.setContentText("Context");
                notificationBuilder.setTicker("TickerText");
                notificationBuilder.setWhen(System.currentTimeMillis());
                notificationBuilder.setSmallIcon(R.drawable.ic_stat_icon);

                Intent notificationIntent = new Intent(this, service.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                                notificationIntent, 0);

                notificationBuilder.setContentIntent(contentIntent);

                notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
                                | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

                mNotificationManager.notify(1,
                                notificationBuilder.build());
    }   }

和清单

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
<uses-permission android:name="android.permission.BATTERY_STATS">
<receiver android:name="MyScheduleReceiver" >
     <intent-filter>
         <action android:name="android.intent.action.BATTERY_LOW" />
     </intent-filter>

 </receiver>
 <service android:name="service" >
 </service>

我希望显示电池电量低的通知不会出现..如果我用BOOT_COMPLETED更改操作并重新启动设备工作..为什么?

1 个答案:

答案 0 :(得分:0)

看看这个答案:https://stackoverflow.com/a/12348778/2508174

看起来你需要以编程方式订阅这些意图。看起来你不需要BATTERY_STATS权限来做到这一点。

希望有所帮助