Rohit Mishra
Rohit Mishra

Reputation: 281

Resuming activity after enabling network connection from settings

My application fetches json data to populate the recycler view. For this i have to make sure that at each point of time the internet connection must be active .

I am using this code to check that..

    private boolean isOnline() {
            ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting())
            {
                return true;
            }
            return false;
        }

I am showing a connection dialog if the internet is not active

private void showNoConnectionDialog(Context context) {
        final Context ctx = context;
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setCancelable(false);
        builder.setMessage(R.string.no_connection);
        builder.setTitle(R.string.no_connection_title);
        builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which)
            {
                ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

This is working fine and i am able to navigate to the settings to enable the internet connection but how can i resume my activity or relaunch my activity as soon as the user turns on the internet and presses back button. This is to ensure that user needs not to close the application and start again. Please provide some solution

Upvotes: 2

Views: 403

Answers (3)

harshitpthk
harshitpthk

Reputation: 4136

use the following code to get a result back from the WIRELESS settings activity.

startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS), 0);

and implement your code in onActivityResult()

Upvotes: 0

M. Mariscal
M. Mariscal

Reputation: 1328

You should use AsyncTask to make this work, I used to learn from this drawing:

AsyncTask drawing

It's very simple and methods are explicit to understand, take a short look! Hope this helps you!

Upvotes: -1

Sasi Kumar
Sasi Kumar

Reputation: 13348

@Override
public void onResume() {
super.onResume();
if(isOnline() )
{
   // call your method
 }
else
{
   showNoConnectionDialog(context); //display dialog
 }
}

Upvotes: 1

Related Questions