如何将值从广播类传递到服务类?

时间:2018-08-14 20:49:38

标签: java android android-intent android-service

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, "my.email@gmail.com",numbersms,bodysms);
         sm.execute();
    }
    return 0;
}
@Override
public IBinder onBind(Intent p1) {
    // TODO: Implement this method
    return null;
}

但不知道 getIntent 到EmailSms.java服务中。不要传递值。

1 个答案:

答案 0 :(得分:0)

使用您在onStartCommand处收到的Intent实例作为参数,它应该是:

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