因此,我正在尝试创建一个电池统计安卓应用程序,但我既不能接收使用broadcastmanager的broadcast,因为它不适用于安卓奥利奥和我的service在后台运行超过几分钟。我的问题是,我如何接收电池广播,如插头,拔出,电平.....在android oreo api 26+上的后台
我从销毁的活动中运行服务
/////my service code/////
public class bservice extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter ifl = new IntentFilter();
registerReceiver(bcr,new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_POWER_CONNECTED));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(bcr,new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(bcr,ifl);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
update();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Log.d("msg","running in background 1");
return Service.START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver bcr = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
update();
Log.d("msg","running in background 2");
}
};
@Override
public void onDestroy() {
super.onDestroy();
//unregisterReceiver(bcr);
Log.d("msg","service destroyed");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this,bservice.class));
Log.d("msg","serv restarted");
}
}
void update()
{.......... my updating code
updaten(pct,cc,isCharging,isCharging);
}
Notification notification;
NotificationManager notificationManager;
void updaten(float pct,float cc,boolean a,boolean ot)
{.........my notification update code
notificationManager.notify(id, notification);
}
}
}发布于 2018-04-12 17:48:22
使用JobIntentService代替Service,然后从服务中动态注册广播接收器。
https://developer.android.com/reference/android/support/v4/app/JobIntentService.html
https://stackoverflow.com/questions/49130582
复制相似问题