您好,我的要求是從特定的號碼接收短信。我想在textview中顯示收到的信息,但我無法從我的活動中從BroadcastReceiver中獲取值。我不知道我做mistake.please告訴我如何調用BroadcastReceiver到活動
我的代碼是
SmsReceiver
public class SmsReceiver extends BroadcastReceiver {
public String str=null;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
//for get sms from special number===============================
String msg_from = msgs[i].getOriginatingAddress();
Log.v("msg_from >>",msg_from);
if(msg_from.equals("XXXXXXXX"))
{
//===============================
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
Intent act = new Intent(context, MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message", str);
context.startActivity(act);
this.abortBroadcast();
}
}
// ---display the new SMS message---
// Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
MainActivity
public class MainActivity extends Activity {
private TextView showText;
private String receivedSms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
receivedSms =intent.getStringExtra("message");
Log.e("mysms", receivedSms);
showText = (TextView)findViewById(R.id.showText);
showText.setText(receivedSms);
}
}
發生了什麼錯誤? –
當Log.e()消息打印時,如果我刪除Log.e它不顯示任何值從textview – Durga
receivedSms是空? –