我在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
将不再起作用)?以及如何传递意图?
反正这行得通吗?还是有另一种方法?