Exiting an Android Application On back button - android

I have an application in which I have different activities. In 1 activity, I want that when the user presses the back button, I want the application to be closed and home screen is displayed
Code
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Really Exit ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
When I run this and press the back button, the home screen is displayed, but when I run it for the second time, I get a console output as
ActivityManager: Warning: Activity not started, its current task has been brought to the front.
And the activity in which the back button is pressed gets displayed.
I think the application does not get killed and runs in background. Just to mention, this is not the starting activity of my application.
Can somebody help me, I am beginner.

Try this code :
#Override
public void onBackPressed()
{
moveTaskToBack(true);
}
Also check this Link

For each and every Intent you have used for going into other activity u have to follow this way for passing intent just pass flag to each intent as given below and after starting Activity using startActivity() u have to add finish() after that demo code as given below
Intent i=new Intent(firstActivity.this,secondActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();

You cannot kill your application at your will. The android OS will do it when it wishes to free the resources allocated to it. You cannot actually implement the exit application concept in android. The user can simply navigate away from your Activity and return to it. If it has to be restarted from the first Activity or resumed where it left, is upto the android OS, not you.
Read this post to understand the philosophy of how android apps should be designed and why you wouldn't want to exit at your will:
Is quitting an application frowned upon?

Add finish(); after that line startActivity(intent) it finish your activity.
Thanks

you need to include this class as such in your code.........
public abstract class AppBaseActivity extends Activity {
public static final String FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION = "com.hrupin.FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION";
private BaseActivityReceiver baseActivityReceiver = new BaseActivityReceiver();
public static final IntentFilter INTENT_FILTER = createIntentFilter();
private static IntentFilter createIntentFilter(){
IntentFilter filter = new IntentFilter();
filter.addAction(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION);
return filter;
}
protected void registerBaseActivityReceiver() {
registerReceiver(baseActivityReceiver, INTENT_FILTER);
}
protected void unRegisterBaseActivityReceiver() {
unregisterReceiver(baseActivityReceiver);
}
public class BaseActivityReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION)){
finish();
}
}
}
protected void closeAllActivities(){
sendBroadcast(new Intent(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION));
}
}
Then you need to extend all other classes from this class just as in an example below:
public class FirstActivity extends AppBaseActivity implements OnClickListener {
/** Called when the activity is first created. */
private Button buttonOpenNextActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
registerBaseActivityReceiver();
buttonOpenNextActivity = (Button)findViewById(R.id.buttonOpenNextActivity);
buttonOpenNextActivity.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
unRegisterBaseActivityReceiver();
}
#Override
public void onClick(View v) {
/* OPEN SECOND ACTIVITY.*/
startActivity(new Intent(this, SecondActivity.class));
}
}
Another class:
public class SecondActivity extends AppBaseActivity implements OnClickListener {
private Button buttonOpenNextActivity;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
registerBaseActivityReceiver();
buttonOpenNextActivity = (Button)findViewById(R.id.buttonOpenNextActivity);
buttonOpenNextActivity.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
unRegisterBaseActivityReceiver();
}
#Override
public void onClick(View v) {
/* OPEN THIRD ACTIVITY.*/
startActivity(new Intent(this, ThirdActivity.class));
}
}
Last Class:
public class ThirdActivity extends AppBaseActivity implements OnClickListener {
private Button buttonCloseAllActivities;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
registerBaseActivityReceiver();
buttonCloseAllActivities = (Button)findViewById(R.id.buttonCloseAllActivities);
buttonCloseAllActivities.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
unRegisterBaseActivityReceiver();
}
#Override
protected void onBackPressed() {
closeAllActivities();
super.onBackPressed();
}
}
Now when you press back button in third activity all other activities will also be finished altogether.
1/ dont forget to register the reciever in onCreate and unregister() it in ondestroy().

Your question is not clear dear.
As per my knowledge you should use broadCast Reciever for finishing the application and passing the intent to home Screen.
MoreOver Warning is nothing , before running your application just press Enter in your code or give sm space and den save it and re- run you appication.It will work fine....

if you want to exit your application on back press then you have to finish all the previous activities when you press the back button on that screen for this you should use the concept of BROADCAST RECIEVER ...... means you have broadcast an intent on that back press which will finish all the previous activities.

Related

Activity minimize in android

Im working on offline login based application using SQLite. For the purpose of security i need to move to login activity if the app has minimized. i tried this code in onPause function
#Override
protected void onPause() {
Intent intent = new Intent(dashboard.this, login.class);
startActivity(intent);
finish();
super.onPause();
}
when i try to move from that activity to another also it moves to the login activity. i hope when im moving to another activity current activity is set to paused. that's why it moves to login activity.
you must set a Boolean to handle loginActivity ;
boolean mustGoToLoginActivity=true;
when you want to go to another Activity first set this boolean to false for example :
public void goToAnotherActivity(){
mustGoToLoginActivity=false;
//...
startActivity(anotherActivity);
}
and in onResume() methode set taht to true .
then in onPause() method :
#Override
protected void onPause() {
if(mustGoToLoginActivity){
Intent intent = new Intent(dashboard.this, login.class);
startActivity(intent);
finish();
}
super.onPause();
}
You are right, this scenario will not work. What you can do is use a static boolean to achieve the behavior like this.
public class MainActivity extends AppCompatActivity {
static Boolean navigateToLogin =false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (navigateToLogin) {
move();
navigateToLogin =false;
}
}
private void move() {
Intent intent = new Intent(this, newActivity.class);
startActivity(intent);
}
#Override
protected void onPause() {
super.onPause();
navigateToLogin = true;
}
}

Close app in onBackPressed()'s MainActivity

I want my app to close when I press the back button on MainActivity. Currently when I press it on MainActivity, it returns to previous activity.
#Override
public void onBackPressed() {
YourActivity.this.finish();
}
It's worth noting that changing the default behavior is not a good idea.
You can use System.exit(0).
#Override
public void onBackPressed() {
System.exit(0);
}
Why would you want your app to not go back to previous activities?
If your MainActivity is started by an activity you don't want to go back to, its better to add flags to the intent that started MainActivity so the previous activity would not stay in the Task-stack.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
If you dont want to do that, you must override the OnBackPress() to remove/finish the Tasks under the MainActivity in the stack.
This can be done with a LocalBroadcaster for example, even though its quite ugly.
In the activity you want to close:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("Your filter");
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}
In your MainActivity:
#Override
public void onBackPressed() {
Intent intentBroadcast = new Intent("Your filter");
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intentBroadcast);
finish();
}

How to call unregisterReceiver on a BroadCastReceiver

I have a couple of activities that extends from a custom class I wrote which in turn extends from Activity. I've named this class LoginFinisherActivity and on overriden its onCreate function like this
private BroadcastReceiver finishReceiver = null;
public static final String ACTION_FINISH_LOGIN = "ACTION_FINISH_LOGIN";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("LoginFinisherActivity", "onCreate() called.");
finishReceiver = new FinishReceiver();
registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH_LOGIN));
}
Now the activities that extended LoginFinisherActivity are the ones that need to retain their states whenever I click the system's back button. i.e. I'm at a welcome activity and I want to go to and forth to a sign up/sign in activities. But when I either sign in or sign up, I land on NavigationActivity which extends Activity, i.e. it needs to be closed down not gone back to whichever activity it came from.
I was able to do that if I removed the onPause and onResume functions from the LoginFinisherActivity.
My FinishReceiver's code is as follows:
private final class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH_LOGIN)) {
finish();
}
}
}
Thank you for your help in advance.
Edit: following are the overriden onPause and onResume functions in the LoginFinisherActivity
#Override
protected void onPause() {
Log.d("LoginFinisherActivity", "onPaused() called.");
super.onPause();
if(finishReceiver != null) {
unregisterReceiver(finishReceiver);
finishReceiver = null;
}
}
#Override
protected void onResume(Context context, Intent intent) {
Log.d("LoginFinisherActivity", "onResume() called.");
super.onResume();
if (intent.getAction().equals(ACTION_FINISH_LOGIN)) {
finish();
}
else {
if(finishReceiver == null)
registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH_LOGIN));
}
}
Assuming you want to finish your activities on successful login/register, I think the best approach would be using startActivityForResult(Intent intent, int REQUEST_CODE) instead of handling more intents that make the flow more complex.
You can also make use of android.support.v4.content.IntentCompatIntentCompat.makeRestartActivityTask(...) if you want to terminate the previous stack of activities.
Hope it helps.

Android launch various activities

first sorry for my english i speak spanish and my english is very bad.
i have a simple android application, this one:
MainActivity with one button to finish:
public class MainActivity extends Activity {
Button boton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boton = (Button)findViewById(R.id.button1);
boton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
}
}
And I have a BroadcastReceiver:
public class BootReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}}
When android start launch the application perfectly, but if i press the home button and then start the application, open a new activity, if i prees button of my app to close the activity it close but appears the old activity (MainActivity). What is the problem??
Thanks!!
what you want is to use a service to run your activity in the background so whenever you minimize your activity by pressing home button for example then restore it the activity doesn't restart.
so just google for an android service tutorial, it's very simple to implement.

How to call previous Android Activity from Unity Activity

My main activity has a button which launches UnityActivity. I need to finish the UnityActivity and return to previous activity. When pressing the back button it closes the whole application.
What can I do? Thank you!
Edit:
I use the AR player from Qualcomm Augmented Reality (Unity Extension).
I have only one main activity which I start the AR player from Qualcomm Augmented Reality.
Main Activity
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onBtnStartClick(final View v) {
Intent i= new Intent(this,ArPart.class);
startActivity(i);
}
}
AR Player Activity
public class ArPart extends QCARPlayerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return super.onKeyDown(keyCode, event);
}
}
I found it easiest to use the overridden onBackPressed() but to do that you also have to make a change in your Unity project:
void Update ()
{
if (Input.GetKeyUp (KeyCode.Escape)) {
AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
jo.Call ("onBackPressed");
}
}
Then, in your activity class:
#Override
public void onBackPressed() {
// Handle the activity however you want,
// what you do here will be executed when the back button is pressed
}
Also, remember that for this to work as expected, the UnityPlayer object cannot be paused - you should pause it after you've handled the back button press event.
Credit goes to #Frank Nguyen from this thread: Can't pass back event from Unity to android library jar.
use the following code
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
finish();
}
do something like this as follows:
Intent i=new Intent(unityActivity.this,mainActivity.class); // the names of activity as per you program.
startActivity(i);
finish();

Categories

Resources