首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Oreo上运行接收广播的服务?

如何在Oreo上运行接收广播的服务?
EN

Stack Overflow用户
提问于 2018-03-06 20:13:23
回答 1查看 1K关注 0票数 1

因此,我正在尝试创建一个电池统计安卓应用程序,但我既不能接收使用broadcastmanagerbroadcast,因为它不适用于安卓奥利奥和我的service在后台运行超过几分钟。我的问题是,我如何接收电池广播,如插头,拔出,电平.....在android oreo api 26+上的后台

我从销毁的活动中运行服务

代码语言:javascript
复制
/////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);

    }
}
}
EN

回答 1

Stack Overflow用户

发布于 2018-04-12 17:48:22

使用JobIntentService代替Service,然后从服务中动态注册广播接收器。

https://developer.android.com/reference/android/support/v4/app/JobIntentService.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49130582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档