我有一个BroadcastReceiver,我想在其中执行UI线程的一些工作。根据example in the BroadcastReceiver documentation,我首先调用goAsync(),它返回一个PendingResult,然后在我的非UI线程中调用PendingResult.finish()

但是,我得到了NullPointerException,因为goAsync()返回了null

我究竟做错了什么?

这是一个复制行为的简单示例。我使用了targetSdkVersion 27minSdkVersion 23:

package com.example.broadcastreceiverpendingintenttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        PendingResult pendingResult = goAsync();

        AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... voids) {
                Log.i("tag", "performed async task");
                pendingResult.finish();
                return null;
            }
        };

        asyncTask.execute();
    }
}

这是一个简单的Activity调用它:
package com.example.broadcastreceiverpendingintenttest;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    public static final String ACTION = "MY_ACTION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter(ACTION);
        broadcastManager.registerReceiver(new MyReceiver(), intentFilter);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(v -> {
            broadcastManager.sendBroadcast(new Intent(ACTION));
        });
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.broadcastreceiverpendingintenttest.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="232dp"
        android:layout_marginEnd="148dp"
        android:layout_marginStart="148dp"
        android:layout_marginTop="231dp"
        android:text="Press me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

最佳答案

我写了一个JobIntentService代替:

package com.example.broadcastreceiverpendingintenttest;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;

public class MyJobIntentService extends JobIntentService {

    public static final String ACTION = "and....action!";

    static final int JOB_ID = 9001;

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        // TODO check the intent action is valid, get extras etc
        Log.i("tag", "performed my task");
    }
}

它在AndroidManifest中声明如下:
<service
    android:name=".MyJobIntentService"
    android:permission="android.permission.BIND_JOB_SERVICE"
    android:exported="false" />
MyReceiver然后使服务工作入队:
package com.example.broadcastreceiverpendingintenttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent jobIntent = new Intent();
        jobIntent.setAction(MyJobIntentService.ACTION);
        MyJobIntentService.enqueueWork(context, MyJobIntentService.class, MyJobIntentService.JOB_ID, jobIntent);
    }
}

开销比我想要的多一点,但是可以完成工作。

关于android - BroadcastReceiver goAsync()返回空PendingResult,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49501196/

10-10 23:34