gpt4 book ai didi

android - JobIntentService 未正常启动

转载 作者:行者123 更新时间:2023-12-02 04:30:38 48 4
gpt4 key购买 nike

在 com.example.project.packageA 包中,我有一个扩展 JobIntentService 的类,定义如下:

public class MyService extends JobIntentService {

static final int JOB_ID = 1000;
static final String TAG =MyService.class.getSimpleName();

public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, MyService.class, JOB_ID, work);
}

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
super.onCreate();
}

@Override
public void onDestroy() {
super.onDestroy();
}

/**
* We have received work to do. The system or framework is already
* holding a wake lock for us at this point, so we can just go.
*/
@Override
protected void onHandleWork(Intent intent) {
Log.i(TAG, "Started onHandleWork");
String value = intent.getExtras().getString("Key");
Log.i(TAG, value);
}

}

在另一个包中:
com.example.project.packageB;我想调用这个服务在后台启动,所以我这样做了:
Intent it = new Intent();
it.setComponent(new ComponentName("com.example.project", "com.example.project.packageA.MyService"));
it.putExtra("Key", "Value");
MyService.enqueueWork(context, it);
Log.d(TAG, "Call successful");

我还在 list 文件中包含以下权限:
<service
android:name="com.example.project.MyService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>

但是,当我运行我的程序时,它看起来并没有启动服务。我可以看到日志消息“调用成功”,但我看不到来自 onHandleWork 函数的日志消息。我是否以错误的方式启动服务?

最佳答案

在更高版本的 Android 中,Google 引入了 Doze 功能以优化设备的电池生命周期。 (不确定他们是从哪个版本引入的)您需要将此添加到您的 Intent 中以忽略电池优化

//禁用电池优化

Intent intent = new Intent(this,SeriesService.class);
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm.isIgnoringBatteryOptimizations(packageName))
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
else { intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
}
startService(intent);

我在我的 OnePlus 5(运行 Android pie)上试过这个,它可以工作

编辑

以防万一我在我已经启动它之后添加我如何调用我的服务
Context con = getView().getContext();//activity context
Intent intent = new Intent(con,SeriesService.class);
intent.setAction(SOME_ACTION);
intent.putExtra(KEY,data);
SeriesService.enqueueWork(con,intent);

关于android - JobIntentService 未正常启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49318311/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com