I have a serious issue about passing data from BroadcastReceiver
to an Activity
. Let see my issue carefully. I have a class PhoneStateReceiver ex
So I understand you don't want to recreate your Activity everytime.
In your Intent
changing this flag will help you :
intent_phonenum.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
In Intent class if you read method summary of FLAG_ACTIVITY_CLEAR_TOP
:
- If set, and the activity being launched is already running in the
- current task, then instead of launching a new instance of that activity,
- all of the other activities on top of it will be closed and this Intent
- will be delivered to the (now on top) old activity as a new Intent. (you can read more ...)
In this case: If your app is running and you have an Activity instance then Intent
will not recreate your Activity. But assume that your app is in closed state and when BroadcastReceiver triggered, the Intent
will create new Activity because you don't have instance of that Activity.
@Edit :
You can specify special Intent like that in your BroadcastReceiver
:
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
Intent i = new Intent("mycustombroadcast");
i.putExtra("phone_num", incomingNumber);
context.sendBroadcast(i);
}
Then in your Activity inside onCreate()
register receiver like that :
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int incoming_number= bundle.getInt("phone_num");
Log.e("incoming number", "" + incoming_number);
}
};
//then register receiver like that :
registerReceiver(broadcastReceiver, new IntentFilter("mycustombroadcast"));
You can unregister Receiver in onDestroy()
: unregisterReceiver(broadcastReceiver);
Also another way is overriding onNewIntent()
in your Activity:
@Override
protected void onNewIntent(Intent intent) {
//your intent is here, you can do sth.
super.onNewIntent(intent);
}