Search code examples
androidandroid-activityback-stackandroid-internet

Close Application if no internet connection


OnCreate of my "Home" activity, I want to check if there's internet connection, if false just close my activity showing a toast..
But, my Home Activity could not be the first on stack, so if just set finish(); it could just close this activity and show the top one in activity stack..
So I've written down this code, but does it make any sense?

 if(!Utils.isOnline(mContext))
        if(!moveTaskToBack(true))
            finish();

Where Utils.isOnline() is just my method to check internet connection

EDIT: I've already created my method to check internet connection and it's Utils.isOnline().. So I'm not asking how to check internet connectio...

EDIT2: moveTaskToBack() probably is not best choice to achieve my target, because yes it puts my activity onBackGround but if I reopen it, app doesn't check anymore my condition (Don't know why.. it skips onCreate(?)) and shows a blank activity..


Solution

  • If you want to close your app you can add this lines:

    Intent intent = new Intent(Intent.ACTION_MAIN);
           intent.addCategory(Intent.CATEGORY_HOME);
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);