Reputation: 365
Below is my code to exit my app.
Since I have more than 1 activity, where should I put exitBy2Click()
so it can be use for all activities?
I tried to create a new class called "Global", and public exitBy2Click()
, but Toast.makeText(this,...
not work.
Thanks.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
exitBy2Click();
}
return false;
}
private static Boolean isExit = false;
private void exitBy2Click() {
Timer tExit = null;
if (!isExit) {
isExit = true;
Toast.makeText(this, "click again to quit", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
}
}, 2000);
} else {
finish();
System.exit(0);
}
}
Upvotes: 0
Views: 109
Reputation: 30088
The best place to put this code is literally "nowhere". Forcibly terminating an Android app is not recommended, and calling System.exit is definitely not something you should ever do in an Android app.
Upvotes: 2
Reputation: 18677
Checking your method, I think that best option would be Inheritance..
Note on example below that you can override onBackPressed()
instead of onKeyDown()
public class BaseActivity extends Activity {
private static Boolean isExit = false;
@Override
public void onBackPressed() {
exitBy2Click();
}
public void exitBy2Click() {
Timer tExit = null;
if (!isExit) {
isExit = true;
Toast.makeText(this, "click again to quit", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
}
}, 2000);
} else {
finish();
System.exit(0);
}
}
}
Then, your "real" activities can extends that BaseActivity
and this way, onKeyDown
and exitBy2Click
will be commom to all classes.
public class MainActivity extends BaseActivity {
@override
public void onCreate(Bundle savedInstance) {
}
}
public class SecundaryActivity extends BaseActivity {
@override
public void onCreate(Bundle savedInstance) {
}
}
//ETC
Upvotes: 3