Search code examples
javaandroidandroid-intentandroid-service

How pass value into service class from broadcast class?


SimpleSmsReciever.java

public class SimpleSmsReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Bundle pudsBundle = intent.getExtras();
    Object[] pdus = (Object[]) pudsBundle.get("pdus");
    SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
    // Start Application's  Service
    Intent startemailsms=new Intent(context,EmailSms.class);    startemailsms.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   startemailsms.putExtra("numbermsg", messages.getOriginatingAddress());
    startemailsms.putExtra("bodymsg", messages.getMessageBody());
    context.startService(startemailsms);
    }
}

EmailSms.java

public class EmailSms extends Service{
@Override
public int onStartCommand (Intent intent, int flags, int startId){
    super.onStartCommand(intent, flags, startId);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
         String bodysms=bodymsg;
         String numbersms=numbermsg;
         SendMail sm = new SendMail(this, "[email protected]",numbersms,bodysms);
         sm.execute();
    }
    return 0;
}
@Override
public IBinder onBind(Intent p1) {
    // TODO: Implement this method
    return null;
}

but unknow getIntent into EmailSms.java Service..dont passing value..


Solution

  • Use the Intent instance you received as argument at onStartCommand it should be:

    public int onStartCommand (Intent intent, int flags, int startId) { //argument to receive
        super.onStartCommand(intent, flags, startId);
        Bundle extras = intent.getExtras(); //using argument
        // Rest as is