开发者

Application Is stop if i pressed Back Button In Android

i have created one application it contains Progress bar with maximum limit.if i press start for starting my progress bar progress bar starts in background a开发者_JS百科nd got message box in application only. But if i press BACK button then my application get stop.. i want my application running in background though i press BACK button..So please tell me how to achieve this..if want code of my application then let me know...


try this

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
            if(keyCode==KeyEvent.KEYCODE_BACK){
                moveTaskToBack(true);
            }
            return super.onKeyDown(keyCode, event);
}


You either need to save the state of your android application when back button is pressed. (save all application data in onPause and reuse it when the application is started again) or use a Service to keep it running in the background when Android closes your app.

Something more convenient is an IntentService if your service is like a single task (for example a file upload or download). An IntentService will finish automatically after the task is over.

Also, make sure you are not doing any of these operations in the UI thread. If the thread is blocked for more than a certain amount of time then Android will think that your app is non-responsive and will force the user to close the app. Move all long running operations to another thread using an AsyncTask.


You can use the concept of Service as a solution for running it in background.


@rohit If the android version is lower than 7 onBackPressed() is not yet implemented. Then use the following snippet and it should work.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (  Integer.valueOf(android.os.Build.VERSION.SDK) < 7 //Instead use android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        // Take care of calling this method on earlier versions of
        // the platform where it doesn't exist.
        onBackPressed();
    }

    return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
    // This will be called either automatically for you on 2.0
    // or later, or by the code above on earlier versions of the
    // platform.

    doSomething();
    return;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜