Closing running Application from BroadcastReceiver - android

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

Related

Pass SMS from BroadcastReceiver to Activity

I am creating an SMS app. I can send messages fine, however I cannot get it to receive. I have successfully implemented the functionality to allow the app to be selected as the default SMS application on the device.
The problem I have is that I cannot pass the SMS from the BroadcastReceiver to the Activity that displays messages. I am aware of the ability to use intent.putExtra() for the message and then startActivity(), but what happens if that activity has already been started when the message is received? I do not want to restart the activity every time a new message is received.
There are few ways to skin that cat, one way is to have a receiver inside the Activity something like this
void onResume(){
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mSmsReceiver, filter);
}
void onPause(){
super.onPause();
unregisterReceiver(mSmsReceiver);
}
private BroadcastReceiver mSmsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Do you stufff
}
};

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.

start activity if application is visible

I am implementing session timeouts in my application.
here what i want to do is launch the login activity if and only if the application is visible (i.e. shown) else i don't want to do anything as when the application is laucnced again it will automatically start off with login Activity itself..
final List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (RunningTaskInfo runningTaskInfo : tasks) {
runningactivities.add(0,runningTaskInfo.topActivity.toString());
}
But this doesn't work for me as it launches the Login Activity in both cases..
Please Help!!
Thanks
One solution is to use intent receivers in your activity. You can register a receiver in the Activity(or activities) that you only want the new activity to be launched from. Then you can launch the new activity with sendBroadcast(intent). You should register and unregister you reciever in each activity as shown below:
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter(CONSTANT_FOR_INTENT);
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//handle the intent here - launch activity, etc
}
};
Now you can launch your activity with this:
Intent intent=new Intent(CONSTANT_FOR_INTENT);
sendBroadcast(intent);
You can also use sendOrderedBroadcast to set a priority and do something else with the intent if your activity is not running.

Finishing an Activity from a Broadcast Receiver

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();
}

Intent not received by activity

I have a main activity that launches a service to do a web search in the background and I would like the main activity to get an intent when the search is done.
In my main activity , I defined a BroadcastReceiver and an Intent Filter to listen to the "end of search" intent:
public class AgeRage extends Activity {
// Listener to all results from background processes
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ImageSearchService.SEARCH_RESULT_ACTION)) {
0);
Toast.makeText(context,"Got " + i + "results", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(context,"unknown intent", Toast.LENGTH_SHORT).show();
}
};
IntentFilter receiverFilter = new IntentFilter ();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Register to image search service messages
receiverFilter.addAction(ImageSearchService.SEARCH_RESULT_ACTION);
registerReceiver(receiver,receiverFilter);
...
In the service , I do the search and when it is done , I send an Intent:
public class ImageSearchService extends IntentService {
...
protected void onHandleIntent (Intent intent) {
... doing search ...
Intent i = new Intent (this,AgeRage.class);
i.setAction (SEARCH_RESULT_ACTION);
i.putExtra(SEARCH_STATUS, (searchStatus ==SearchStatus.DONE) ? true:false);
i.putExtra (SEARCH_RESULT_NUM, totalResultNum);
i.putExtra (SEARCH_ID, searchID);
sendBroadcast (i,null);
}
But, the main activity doesn't get the Intent. I know that the sendBroadcast is being called and the the receiver's OnReceive is not (checked with a debugger).
I assume that since I create the filter dynamically , I do not need to define a filter in the manifest file.
Am I doing something wrong ?
Thanks
Isaac
Ok. Well I just checked mine and we are doing it the same way, however ...
ImageSearchService.SEARCH_RESULT_ACTION
Try doing com.yourpackagename.ImageSearchSrvice.SEARCH_RESULT_ACTION
where SEARCH_RESULT_ACTION is a public static string variable. See if that helps.
I think it must be the naming of the ACTION. Also note that you might want to run tru the breakpoints and just check log. do intent.getAction() and print this out rather than checking inside the if statement. Just always print it out and see. Don't need to break inside a broacast receiver it will crash after a while.

Categories

Resources