Reputation:
I need to send message from SmsReceiver
Class to My Main_Activity and can't do it. I tried out very much and searched But... .
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
Intent intent1=new Intent(context, MainActivity.class);
intent1.putExtra("m",message);
context.sendBroadcast(intent1);
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText intext=(EditText) findViewById(R.id.editText2Inputtext);
BroadcastReceiver mysms=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
String sms=arg1.getExtras().getString("m");
intext.setText(sms);
}
};
}
}
Upvotes: 3
Views: 8812
Reputation: 5960
Your code to send and register broadcast receiver not correct. Send broadcast:
Intent intent = new Intent("your_action_name");
intent.putExtra(....);
sendBroadcast(intent);
receive:
BroadcastReceiver mysms=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
String sms=arg1.getExtras().getString("m");
intext.setText(sms);
}
};
registerReceiver(mysms, new IntentFilter("your_action_name"));
and remember to unregister when destroy your activity.
Upvotes: 5
Reputation: 2114
Instead of context.sendBroadcast(intent1);
you should try context.startActivity(intent1);
try this
Intent i = new Intent(context,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(i);
Upvotes: -1