Reputation: 1201
I want to send broadcast message to an application and then receive it from current activity. I can send broadcast message but then it couldn't received from broadcast receiver. Here is my code;
public class LogIn extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//toast message received !
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
//send broadcast message
Intent i = new Intent(LogIn.class.getName());
getContext().sendBroadcast(i);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(LogIn.class.getName()));
}
@Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(receiver);
} catch (Exception e) {}
}
}
What is the problem that I missed ? Thank you for your help..
Upvotes: 0
Views: 1305
Reputation: 39191
Have a look at the diagram for an Activity
's lifecycle. The onCreate()
method runs before onResume()
, so your sending the broadcast before you've registered the Receiver.
I'm not sure why you'd want to broadcast to the same class, but you can solve your issue by calling the registerReceiver()
method in onCreate()
as well, before the sendBroadcast()
call.
Upvotes: 3
Reputation: 4907
you are registering your receiver with different intent and sending the broadcast with different intent. Thats why you are not receiving your broadcast.
public class LogIn extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
//send broadcast message
Intent i = new Intent("com.abc");
getContext().sendStickyBroadcast(i);
}
private BroadcastReceiver receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//toast message received !
}
};
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter("com.abc"));
}
@Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(receiver);
} catch (Exception e) {
}
}
Add Permission
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
Upvotes: 0