Ash
Ash

Reputation: 690

How to pass data from Service to Broadcastreceiver

I am calling broadcast receiver from service through this method.

   Intent intent = new Intent(NotifyService.this, AlarmReciever.class);
   intent.putExtra("TIME",ttime);
   PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),    34324243, intent, 0);
   AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
   alarmManager.set(AlarmManager.RTC_WAKEUP,timee,pendingIntent);

In Broadcastreceiver page I am receiveing through this method.

   Bundle b = in.getExtras();   
   date = b.getString("TIME");

Problem is In Broadcastreceiver page I am getting null value. My Question is :-

How to pass data from service to broadcastreceiver ?

Upvotes: 1

Views: 3119

Answers (3)

Barun
Barun

Reputation: 312

you missed to do like this:-

Intent intent = new Intent(NotifyService.this, AlarmReciever.class);
sendBroadcast(intent);

You can call pendingIntent Like this:-

    PendingIntent operation = PendingIntent.getBroadcast(Service.this,
            0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(),5* 60 * 1000, operation);

If you are passing any time data to broadcast class,then you can receive that data in receiver class as

String mTime = NotifyService.time;

Try this. Inform me also.

Upvotes: 0

amIT
amIT

Reputation: 684

OK i assume the "ttime" is a bundle ( from the code your wrote it seems to make sense)

Try and recieve the data like this

   Bundle b=  in.getBundleExtra("TIME");

In case the "tttime" is of other format say a String or Int you can get the data in onReceive of Broadcastreceiverlike this

String :

in.getStringExtra("TIME");

Integer :

in.getIntExtra("TIME", -1) // -1 is  default value  which  will be  return incase  no matching integer  found with the key "TIME" in intent "in"

For full details and how to get data from intent of different type refer to android documentation

Upvotes: 0

Jigar
Jigar

Reputation: 791

In your main activity start your service as

i = new Intent(this, SimpleService.class);
startService(i);
registerReceiver(broadcastReceiver, new IntentFilter(SimpleService.BROADCAST_ACTION));

use send broadcast to send any value from service class to mainactiviy class as

intent.putExtra("textval", s);
sendBroadcast(intent);

and then in your main activity class receive it as

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //do your coding here using intent
        }

    };

Upvotes: 2

Related Questions