user2134412
user2134412

Reputation:

Onclick back button the application stops

I have one problem regarding my app,when i click back button my application is getting finish.i need to prevent it.How could i make it .

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);

   startActivity(setIntent);
} 

I have tried something like this.But its not working .Actually what i need is when i will click back button ,the application should not finish it should run in background.can anybody help me out.@Thanks

Upvotes: 0

Views: 3114

Answers (2)

bogdan
bogdan

Reputation: 782

What do you mean by "it should run in background"? Why would you want that? If the user wants to keep the app opened, he can use the home button and the app won't be closed, if he presses the back button he wants to close the app. If want to have something that is still running even after the user closes the application you should take a look at Service http://developer.android.com/reference/android/app/Service.html, this will continue running even after the user closes the app

Upvotes: 2

waqaslam
waqaslam

Reputation: 68187

Try doing it like this:

@Override
public void onBackPressed() {
    Log.d("CDA", "onBackPressed Called");
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);

    startActivity(intent);
}

By doing this, your activity will not be destroyed (i.e. onDestroy will not be raised). But also, there's no guarantee that Android will preserve your activity for long.

In case, you are running a process that you want to keep on running even in background, then I would suggest you to go for Service or IntentService.

Upvotes: 2

Related Questions