所以我正在尝试创建一个电池统计Android应用程序,但我都无法使用broadcast
来接收broadcastmanager
因为它不适用于android oreo而我的service
也没有运行在背景上超过几分钟。
我的问题是如何在android oreo api 26 +背景下接收插头,拔出,等级.....等电池广播。
我从destroy
上的活动运行服务/////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);
}
}
}
答案 0 :(得分:0)
使用JobIntentService
代替Service
,然后从服务中动态注册广播接收器。
https://developer.android.com/reference/android/support/v4/app/JobIntentService.html