我必须创建一个服务,根据电池百分比显示通知。问题是它不能正常工作。
public class Battery extends Service {
BroadcastReceiver batteryInfoReceiverLevel;
Notification notification;
Context context;
int level;
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void BatteryLevel(Context mContext) {
notification = new Notification();
batteryInfoReceiverLevel = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if(level <=100) {
//Show notification 01
} if(level == 100) {
//Show Notification 02
}
}
};
mContext.registerReceiver(batteryInfoReceiverLevel, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
此服务必须在启动时启动,因此我创建了此类
public class ServiceBoot extends BroadcastReceiver {
Intent intent;
@Override
public void onReceive(Context context, Intent intent2) {
// TODO Auto-generated method stub
intent = new Intent(context, Battery.class);
context.startService(intent);
}
}
在我的清单中,在标签
中<service android:name="Battery"></service>
<receiver android:name="ServiceBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
相对许可RECEIVE_BOOT_COMPLETED。现在,只要您打开手机,服务就会正常启动,但即使条件为真,也不会显示任何通知。我确信变量级别不是NULL。奇怪的是,如果在我的应用程序的任何活动中使用此代码
Battery bat = new CheckBattery();
bat.BatteryLevel(getBaseContext());
效果很好,因为它会显示通知。问题出在哪里?我该如何解决?