Android-不允许从JobIntentService启动服务意图:应用程序在后台

时间:2020-09-04 04:13:04

标签: java android

我在BroadcastReceiver中收到意图,并试图启动服务。

由于我在后台运行应用程序时无法运行服务,因此我尝试使用JobIntentService来将我的意图传达给普通服务:

public class JsInvokerJobService extends JobIntentService {

    ...
    @Override
    protected void onHandleWork(Intent intent) {
        // 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.
        Log.i(TAG, "Executing work: " + intent);
        this.startService(intent);
        Log.i(TAG, "Finished work: " + intent);
    }

但是,这仍然会导致我的应用在后台运行时出现错误:

Not allowed to start service Intent app is in background

我已经阅读了有关在这些情况下使用Runnable的信息,但是我不知道如何将上下文传递给Runnable:

    final Handler mHandler = new Handler();
    
    @Override
    protected void onHandleWork(Intent intent) {
        // 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.
        Log.i(TAG, "Executing work: " + intent);
        mHandler.post(new Runnable() {
            @Override public void run() {
                this.startService(intent);
            }
        });
        Log.i(TAG, "Finished work: " + intent);
    }

我如何访问上下文(显然this将不再起作用)?以及如何传递意图?

反正这行得通吗?还是有另一种方法?

0 个答案:

没有答案