简体   繁体   中英

BroadcastReceiver not receiving broadcast from IntentService in Android

I'm sending a progress value like int progress = 10 via Broadcast from IntentService to display the progress of uploading file.

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);
            //...
        }
}

So in my Activity I register the receiver but it is never called.

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);
    }
}

Where could be the problem? What am I doing wrong? Have I forgotten something?

Thanks for any help!

Kind Regards!

try to register you receiver as below -

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

while broadcasting you are sending action as below

broadcastIntent.setAction(SendList.mReceiver.TEST);

and when you register it is different.

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

Your action should be same while sending and receiving. Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM