BroadcastReceiver 在 Android 中未接收到来自 IntentService 的广播

BroadcastReceiver not receiving broadcast from IntentService in Android

我正在从 IntentService 通过 Broadcast 发送类似 int progress = 10 的进度值,以显示上传文件的进度。

protected void onHandleIntent(Intent intent) {

    broadcastIntent = new Intent();
    broadcastIntent.setAction(SendList.mReceiver.TEST);
    try {
        broadcastIntent.putExtra("Count",mArraylist.size());
        [...uploading data...]
        for (int i = 0; i < mArrayList.size(); i++) {
            broadcastIntent.putExtra("progress", i);
            sendBroadcast(broadcastIntent);
            //...
        }
}

所以在我的 Activity 中我注册了接收器,但它从未被调用。

public class SendList extends Activity {
TextView textResult;
ProgressBar progressbar;
boolean mIsReceiverRegistered = false;
BroadcastReceiver receiver;

@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.sendlist);
    textResult= (TextView)findViewById(R.id.maxFragments);
    progressbar = (ProgressBar) findViewById(R.id.progressBar);
}


@Override
public void onResume() {
    super.onResume();
    if(!mIsReceiverRegistered) {
        if (receiver == null)
            receiver = new FragmentReceiver();
        registerReceiver(receiver,new IntentFilter(mReceiver.TEST));
        mIsReceiverRegistered = true;
    }
}

@Override
public void onPause() {
    super.onPause();
    if(mIsReceiverRegistered) {
        unregisterReceiver(receiver);
        receiver = null;
        mIsReceiverRegistered = false;
    }
}

private void updateUI (Intent intent) {
    progressbar.setProgress(intent.getIntExtra("progress", 0));
}

public class mReceiver extends BroadcastReceiver {
    public static final String TEST = "upload";
    @Override
    public void onReceive(Context context, Intent intent) {
        int count = intent.getIntExtra("Count",0);
        progressbar.setMax(count);
        textResult.setText(count);

        updateUI(intent);
    }
}

问题出在哪里?我究竟做错了什么?我是不是忘记了什么?

感谢您的帮助!

亲切的问候!

广播时您正在发送如下操作

broadcastIntent.setAction(SendList.mReceiver.TEST);

和你注册的时候不一样。

registerReceiver(receiver,new IntentFilter(FragmentReceiver.TEST));

发送和接收时您的操作应该相同。 希望对您有所帮助。

尝试按以下方式注册您的接收器 -

IntentFilter filter = new IntentFilter();
filter.addAction(SendList.mReceiver.TEST);
registerReceiver(receiver,filter);