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();
}
Related
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;
}
}
I made two activities for the test.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SubActivity.class));
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
This button in MainActivity can start SubActivity.
public class SubActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
startActivity(new Intent(SubActivity.this, MainActivity.class));
}
}
When in SubActivity, press back button, it doesn't call onDestroy() in SubActivity class and start MainActivity. What I want to do is, How to call SubActivity onDestroy() when I finish the MainActivity? It doesn't call SubActivity onDestroy() when I press the back button in MainActivity. Is there any solution like using Intent.FLAG_ACTIVITY?
You should finish() your SubActivity in onBackPressed to destroy it and go back to your MainActivity, instead of doing a startActivity. In many cases, that is the behavior you'll get even if you don't implement onBackPressed yourself. Your current code is starting a second MainActivity.
The solution proposed here worked for me:
In Java:-
Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
In Kotlin:-
val i = Intent(OldActivity.this, NewActivity::class.java)
// set the new task and clear flags
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
I need to show a Pincode screen when the user is inactive for more than 1 minute.
I found this answer that gave me a good solution for my needs and I implemented it on my BaseActivity.
But now I am having a problem with the onUserInteraction() method, which is being called twice (and triggering my Runnable twice) everytime I press a button and start a new activity, because when I come back after 1 minute to the previous screen, the pincode screen is showing.
I've changed my Runnable to be static, but I lose the context to start the pincode activity.
What could I do to start the activity from the runnable or to make sure the onUserInteraction() is being triggered only when something is tapped on the screen?
My current code:
public class BaseActivity {
private static final String TAG = BaseActivity.class.getSimpleName();
static private Handler disconnectHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(BaseActivity.this, CustomPinActivity.class);
startActivity(intent);
}
};
public void resetDisconnectTimer() {
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, getResources().getInteger(R.integer.disconnect_timeout));
}
public void stopDisconnectTimer() {
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction() {
resetDisconnectTimer();
}
#Override
protected void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
super.onStop();
stopDisconnectTimer();
}
}
Manifest:
<activity
android:name=".CustomPinActivity"
android:launchMode="singleTop"
android:label="#string/title_activity_pincode" />
<activity android:name=".base.BaseActivity"
android:launchMode="singleTop" />
Well, I think the problem is the method onUserInteraction(). The documentation says:
All calls to your activity's onUserLeaveHint() callback will be accompanied by calls to onUserInteraction().
The link here. The documentation for onUserLeaveHint() says:
This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notification.
Second link here.
I understand, that onUserInteraction() method will be called each time an activity is paused, and before the pause. So I would use a flag like:
private boolean mStartingActivity;
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
mStartingActivity = true;
Intent intent = new Intent(BaseActivity.this, CustomPinActivity.class);
startActivity(intent);
}
};
#Override
public void onUserInteraction() {
if(!mStartingActivity)
resetDisconnectTimer();
}
#Override
protected void onResume() {
super.onResume();
resetDisconnectTimer();
mStartingActivity = false;
}
I gess, there are more elegant solutions. I hope it helps.
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.
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.