Finishing an Activity from a Broadcast Receiver - android

I have an Activity that I display as modeless when the phone rings (over the phone app). I would like to finish the Activity when either of the following events occur. The first is if I touch anywhere outside the Activity (this is not a problem), the second is if the ringing stops. I am listening for IDLE_STATE in the broadcast receiver but I am not sure on how to call the finish on the activity when I see it. The receiver is not registered by the activity but by the Manifest.xml

write the code in your receiving broadcast now this will send another broad cast with the intent named "com.hello.action"
Intent local = new Intent();
local.setAction("com.hello.action");
sendBroadcast(local);
Now catch this intent in the activity with you want to finish it and then call the super.finish() on the onReceive method of your receiver
like this
public class fileNamefilter extends Activity {
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction("com.hello.action");
registerReceiver(receiver, filter);
}
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
public void finish() {
super.finish();
};
}
this will finish the activity

What if you register another broadcast receiver from the activity. Then, when you want to kill it, send a broadcast message from the broadcast receiver that you mentioned.

I actually ended up adding a PhoneStateListener in the Activity to listen for IDLE_STATE.

After a long R&D over internet i have solved my problem. The below code is helpful if you start an activity from broadcast receiver and
clear all activity stack instance.
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
moveTaskToBack(true);
}
}

I used this code to solve my problem. finish is the method of Activity, so call Activity and context like:
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.e(TAG, "Inside EXTRA_STATE_IDLE");
((Activity) arg0).finish();
}

Related

My Activity not receiving Local Broadcasts sent from another activity

I'm just getting familiarised with the Local Broadcast Messages. I have 2 activities.
MainActivity :
I have 2 buttons. On the click of 1 button, I'm broadcasting the message. On the click of another one, I'm navigating to second Activity.
public class MainActivity extends AppCompatActivity {
Button btn;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.sendBroadCast);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
btn1 = (Button)findViewById(R.id.btn);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
void sendMessage(){
Log.d("RAK","Gonna send braodcast");
Intent intent = new Intent("customMsg");
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
Second Activity :
Registering for the receiver in onCreate of this activity.
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.d("RAK","In oncreate of second activity.Registered for local receiver");
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("customMsg"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
}
The issue I'm facing is, the second Activity is not receiving the broadcast. Please help me.
P.S : Please dont mark this a duplicate. I have followed this link : how to use LocalBroadcastManager?
Thanks,
Rakesh
So as to receive the broadcast the second activity should be up and running while the first one is sending a broadcast, which is going to be hard in your case (2 activities not running at same time).
Your first Activity sends the broadcast, but no activity (in your case second activity) is launched yet so the messgae get 'lost'.
You could test by broadcasting from within a service for example, and your second activity running. Then, the activity could handle/receive it.
What you may want to do is passing a String to the secondActivity using extraData. If you wish to test BroadcastReceiver, then, try with a service sending the broadcast !
The problem is your registering your broadcast receiver inside onCreate() of second activity, that means the second activity should have been previous launched before you broadcast your intent keeping in mind that your do not unregister it when the second activity is destroyed.
Alternative you can register your receiver statically in the Manifest file
public class Receiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
// Whatever
}
}
Manifest
<receiver
android:name=".Receiver"
android:exported="false" >
<intent-filter>
<action android:name="customMsg" />
</intent-filter>
</receiver>
NOTE:
Registering statically ensure that the the receiver is registered at system boot time or when the application is added at run time

Android LocalBroadcastManager from Fragment to Activity not receiving message

I want to sent a message from a Fragment to an Activity (not the Fragment parent Activity, just another one).
Actually I do the same from a Service to the same Activity and it works great.
This is my code:
Fragment:
private void sendBroadcastMessage() {
Intent intent = new Intent("my_event");
// add data
intent.putExtra("message", "test");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
Activity:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
super.onPause();
}
#Override
protected void onResume() {
super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter("my_event"));
}
I've just followed that great post, but it only works from Service to Activity
I think it has something to do with the Context from the Fragment, maybe getActivity() is not the right way...
Any ideas?
Thanks.
Register broadcast in onCreate and unregister in onDestroy of your activity.
In your case it may be unregister in onPause. so unregister in onDestroy instead of onPause.
Thanks,

Closing running Application from BroadcastReceiver

In my App, there is a condition which check every day and if it gets true then I want my App get close in between the run like a crash and stack also gets clear .
I have try and tested many solutions but didn't find the one that works the way i wanted .
My BroadcastReceiver:
public void onReceive(Context context, Intent intent) {
PreferenceForApp prefs = new PreferenceForApp(context);
Bundle bundle = intent.getExtras();
if (bundle!=null){
if(bundle.containsKey("exception")) {
// String e = bundle.getString("exception")
if(bundle.get("exception").toString().equalsIgnoreCase("http request failed with error_msg No Match Found")) {
prefs.setIsDeviceValidated(false);
prefs.setIsLogIn(false);
Log.i("Time", "Exception Occur");
Intent CSPIntent=new Intent(context,CSPLoginActivity.class);
CSPIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
CSPIntent.putExtra("close_activity", true);
Log.i("Time", "IntentExit");
context.startActivity(CSPIntent);
}
}
}
}
}
And code to finish in an Activity I am calling from broadcastReceiver:
if (getIntent().getBooleanExtra("close_activity",false)) {
Log.i("Time", "ExitCSPLogin");
this.finish();
}
This code is not closing App in between the run.
You need to register BroadcastReceiver in your activity and send broadcast to BroadcastReceiver when you want to close application.
In your Activity try this:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.package.ACTION_CLOSE");;
BroadcastReceiver Receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
registerReceiver(Receiver, intentFilter);
in onDestroy() method of you Activity unregister BroadcastReceiver:
#Override
protected void onDestroy() {
unregisterReceiver(Receiver);
super.onDestroy();
}
Now when you want close application send broadcast to BroadcastReceiver:
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.package.ACTION_CLOSE");
sendBroadcast(broadcastIntent);
Hope this helps!
you have to check below condition in your app's mainActivity's onCreate method every time when user enter in your app. or in onResume if you want to to close your app immediately
if (!prefs.getIsDeviceValidated()) {
Log.i("Time", "ExitCSPLogin");
this.finish();
}
i assume you have more then one activity in your app, so insted of check above flag in every activity we 'll put it in main activity. allow user to use your app until he/she come at mainActivity
Note: create Broadcast Receiver for your App(add in manifest), not for specific activity

send action from receiver to activity?

I am using broadcast receiver in my app to detect incomming call and it works fine. But problem is I can not send action to activity. I mean.. I want do something in activity not in receiver. I read many tutorial but they all are performing action in receiver. Any idea ?
You can declare a BroadcastReceiver as inner class of the Activity. In this case you can directly call activity's methods:
public class MyActivity extends Activity {
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
activityMethod();
}
};
private final IntentFilter filter = new IntentFilter("android.intent.action.PHONE_STATE");
#Override
protected void onStart() {
super.onResume();
registerReceiver(receiver, filter);
}
#Override
protected void onStop() {
super.onPause();
unregisterReceiver(receiver);
}
private void activityMethod() {
}
}
You can start the Activity using an Intent and put a command code in the Intent extra fields. In your Activity you can then decide the behaviour based on the command code or resort to a default behaviour if none is present.
You can start an activity from your receiver via the normal means:
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, YourActivity.class);
startActivity(i);
}
Note though that the user is going to expect that the phone application starts up since they are receiving a phone call. It is very likely a bad idea to hijack the phone call by dumping your own activity on top of the stock dialer app.

Where to register a BroadcastReceiver (Activity lifecycle fun)

Where's the right place to register/unregister an intent receiver in an Activity? Usually I would put stuff like this here:
class MyActivity
{
private BroadcastReceiver mMyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Do something.");
}
};
#Override
public void onResume() {
super.onResume();
registerReceiver(mMyReceiver, new IntentFilter(...));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mMyReceiver);
}
}
The problem is that my activity can then no longer respond to the broadcast if it happens while it's in the pause state. Where's the right place to do something like this then?
Thanks
I think the following link might be useful to you
http://android-journey.blogspot.com/2010/01/android-braodcast-receivers.html
This should work in your case:
Unregister in onDestroy().
I think in your case, you can register the receiver in the onCreate() and unregister in the onDestroy(). This will keep it registered, even after it's been paused, until the activity is destroyed.
I had the reverse problem. I had originally registered my receivers in the onCreate() and when my activity was paused, I still got logs that it was receiving broadcasts. I moved it to the onResume, as you have, and that problem went away.

Categories

Resources