Reputation: 2903
I am trying to shutdown an activity from another application, hence another activity. I am doing this using the BroadcastReceiver class and Intent.
Here's what I do:
In the first Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.update_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("<package name here>");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setAction("finish_activity");
sendBroadcast(intent);
}
});
}
I send a broadcast with a specific action.
In the other app's activity I am doing the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
System.out.println("Received broadcast!!");
Toast.makeText(MainActivity.this, "received broadcast", Toast.LENGTH_LONG).show();
String action = intent.getAction();
if (action.equals("finish_activity")) {
postEvent(new ShutdownEvent());
finish();
// DO WHATEVER YOU WANT.
}
}
};
registerReceiver(broadcast_reciever, new IntentFilter("finish_activity"));
}
Mainly I create the Receiver and I register it. However this doesn't seem to be working, it seems that my code does not execute until here.
Any suggestions highly appreciated.
Thanks!
Upvotes: 0
Views: 1328
Reputation: 4620
In order to expose your BroadcastReceiver to the other apps, you should declare it in your manifest, and mark it as exported
. This way the system knows how to trigger it.
A good article on how to use BroadcastReceivers http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_create
Upvotes: 2