Reputation: 5031
I am launching an activity when receiving a ringing broadcast from the phone however this isn't ended (or closed) once call is answered or aborted. I need to end the activity in my else if but am unsure how to go about this? What would be the best method?
public class CallReceiver extends BroadcastReceiver {
Intent i;
@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
assert state != null;
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
i = new Intent(context, IncomingCall.class);
i.putExtras(intent);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.startActivity(i);
}
else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// WHAT GOES HERE?
}
}
}
Upvotes: 0
Views: 1480
Reputation: 11
You can put the activity object as parameter to the constructor of your BroadcastReceiver. Then call activity.finish() to end the activity.
Upvotes: 0
Reputation: 26027
You can use LocalBroadcast Manager for sending a local broadcast message from within the else
statement inside onReceive
. In the activity(which you want to close) you can register your receiver to receive local broadcasts. Whenever the else
part will be called, you can send a local broadcast which will be received by your Activity. Then in your activity you can call finish()
.
For LocalBroadcastManager
, the docs say:
It is a helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent). One of them is that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.`
This broadcast is only local to your app. So is safe as well. You can see here how to use it: how to use LocalBroadcastManager? . Hope it helps you.
Upvotes: 3