I have written a simple activity to test out services and broacast receivers and a service to go along with it. In order to know whether or not it’s working I’ve set up a Toast within the main activity to be showed once the OnReceive() method is called. But for the life of me I can’t get this to work.
These are the codes:
public class ServicesAndBroadcastIntentActivity extends Activity {
private Toast test;
private Intent intent;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this,serviceD.class);
test = Toast.makeText(this,"Test",Toast.LENGTH_LONG);
test.setGravity(Gravity.CENTER,0,0);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
test.setText((intent.getStringExtra("EXTRA_MSG")));
test.show();
}
};
@Override
public void onResume(){
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(serviceD.BROADCAST_ACTION));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
public class serviceD extends Service{
private Intent intent;
static final String BROADCAST_ACTION = "com.mejg.ServicesAndBroadcastIntent";
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
public void onStart(){
intent.putExtra("EXTRA_MSG","hola");
sendBroadcast(intent);
stopSelf();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
You are calling
startService()beforeregisterReceiver(). Both are asynchronous operations, but they will still likely occur in sequence. Hence,onStart()of your service will be called beforeregisterReceiver()does its work, which means your broadcast goes out before your receiver is set up.For this sort of experimentation, I recommend setting up a basic UI (e.g., one really big button) and doing the
startService()call when the button is pressed.Also, since the service calls
stopSelf(), you do not need to callstopService()from the activity.Also also, you might consider using
LocalBroadcastManagerfor this — same basic syntax with better performance and security, since it all stays within your process.UPDATE
Also also also,
onStart()has been deprecated for two-plus years, and your method signature for it is wrong, anyway. Please useonStartCommand(), with the right parameters.Also also also also, use
@Overridewhen overriding methods, to help you catch these sorts of problems.