Domanda

I've tried to send a Broadcast from a service to an Activity with IntentService, for that I've used the following code:

public class NotifyService extends IntentService {

    public NotifyService() {
        super("NotifyService");
    }

    // will be called asynchronously by Android
    @Override
    protected void onHandleIntent(Intent intent) {

        Log.d("onHandleIntent", "start service");
        publishResults();
    }

    private void publishResults() {

        result = Activity.RESULT_OK;
        Intent intent = new Intent(NOTIFICATION);
        intent.putExtra(RESULT, result);
        sendBroadcast(intent);

    }
}

then I define my Receiver in an Activity class like:

public BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("TAG", "receiver");
        Bundle bundle = intent.getExtras();


        if (bundle != null) {
            int resultCode = bundle.getInt(NotifyService.RESULT);
            if (resultCode == RESULT_OK) {

                Toast.makeText(Home.this, "after service work.", Toast.LENGTH_LONG)
                        .show();                    
            }
        }

         stopService(new Intent(Home.this,NotifyService.class));
    }
};

I've used registerReceiver in onResume and unregisterReceiver in onPause method

registerReceiver(receiver, new IntentFilter(NotifyService.NOTIFICATION));

But the onReceive method not getting called,

I've used section 7 of This Site

what have I missed?

Edit

did I have any alternative solution? I've try to notify activity from service to update data.

È stato utile?

Soluzione

I'm unsure why your original code is not working. However, if you want application-local broadcasts, you might want to use a LocalBroadcastManager instead of regular cross-application broadcasts.

Use this in your service:

LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

and these in your activity:

LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
        new IntentFilter(NotifyService.NOTIFICATION));

LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);

Let me know if this changes anything. Again, I don't see why your original code doesn't work, so this is more of a guess.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top