In my application I am facing this issue where an activity(ex:Activity_B) is getting closed only when back button is pressed twice.I want Activity_B to close when back button is pressed once and Activity_A to display after that.
I tried this code:
public override void OnBackPressed()
{
base.OnBackPressed();
//MoveTaskToBack(true);
this.Finish();
Finish();
FinishAndRemoveTask();
}
But the behaviour is still same.
I tried putting debugger point and see how it behaves.
The Activity_B is getting called when back button is pressed.
The code to start Activity_B is :
private void OnDataLayout_Click(object sender, EventArgs e)
{
Intent intent = new Intent(this, typeof(Activity_B));
StartActivity(intent);
}
Any help is much appreciated.
Update1: I observed that the OnDataLayout_Click event is also getting called twice and after navigating to OnCreate () of Activity_B, the OnCreate() is also getting called twice.
OnDataLayout_Click event is also getting called twice
If your Button's click event was bound twice, the click event will be called twice.
Like below code:
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
initView();
}
protected override void OnResume()
{
base.OnResume();
initView();
}
private void initView()
{
Button bt = FindViewById<Button>(Resource.Id.bt);
bt.Click += Bt_Click;
}
private void Bt_Click(object sender, System.EventArgs e)
{
Intent intent = new Intent(this, typeof(Activity1));
StartActivity(intent);
}
}
The initView method was called twice, OnCreate and OnResume method. This will cause your problem.
But, if you use SetOnClickListener method, the problem will disappear:
public class MainActivity : AppCompatActivity,View.IOnClickListener
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
initView();
}
protected override void OnResume()
{
base.OnResume();
initView();
}
private void initView()
{
Button bt = FindViewById<Button>(Resource.Id.bt);
bt.SetOnClickListener(this);
}
public void OnClick(View v)
{
Intent intent = new Intent(this, typeof(Activity1));
StartActivity(intent);
}
}
If you want to go back to Activity A from Activity B onBackpressed you need not need to write any code for backpressed but if you want to exit on Backprssed from Activity B without going to Activity A then you need to finish() it in Activity A();
Related
I try to run LogIn activity from MainActivity but if I dont add FINISH() after
startActivityForResult, intent wont start
on MainActivity
**pref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean mojpin = pref.getBoolean("PinLock",false);
if(mojpin && loged==false){
Intent i = new Intent(MainActivity.this,AppPinLock.class);
MainActivity.this.startActivityForResult(i,1);
finish();
}**
On LogIn Activity
**String mojpin = getPassword();
if(mojpin!= ""){
String mojpin2 = pass.getText().toString();
if(mojpin.equals(mojpin2)){
naslov.setText("Pin is ok");
Intent i = new Intent(AppPinLock.this,MainActivity.class);
setResult(1, i);
startActivity(i); //if I dont add this wont back to MainActivity
finish();**
Yeah, You shouldn't close MainActivity after calling startActivity();
Explanation: If you start an Activity in MainActivity, the Method
#Override
protected void onPause() {
super.onPause();
}
Will be called. But if you call finish(); after calling the other Activity in the MainActivity, Android instantly Terminates the MainActivity completly and you can't get back until you call the MainActivity again. Example Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(new Intent(this, Activity2.class));
//DO NOT use finish(); here!!! (It will kill this Activity after launching Actiivty2)
}
}
Activity2
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
finish(); //this will close this Activity and you will get back to the last Activity. (In this case MainActivity)
}
}
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 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.