Search code examples
javaandroidsettingsapplication-settings

How to check if data connection is on and if not prompt the user to turn on data services or exit app android


Before shouting that this is a duplicate question, please note that i have gone trough the following articles / questions : One; Two; Three; Four; Five; Six; Seven; Search Query

Ok. Now, since, hopefully we established that I'm not so lazy, just dumb, I can ask for your help : how to check if data connection is on and if not prompt the user to turn on data services or exit app android ?! Please take in consideration that I'm new to Java/XML/Android, and I will require thorough explanations if possible, because everything I've tried so far doesn't work (since incomplete code, obsolete code, poor improvisation and programming skills (mine, of course)). I will settle for the code too, but if accompanied with (some) explanations is for the better, since it is an opportunity for me to understand and learn.

This is the only thing sort of "working" util now (sort of because, it ends allways saying "Error setting mobile data state" even if I have enabled data before running the app ) :

public class WelcomeActivity extends AppCompatActivity {
ImageView imageView;

public void setMobileDataState(boolean mobileDataEnabled)
{
    try
    {
        TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);

        if (null != setMobileDataEnabledMethod)
        {
            setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
        }
    }
    catch (Exception ex)
    {
        //Log.e(TAG, "Error setting mobile data state", ex);
        Context context = getApplicationContext();
        Toast.makeText(context, "Error setting mobile data state", Toast.LENGTH_LONG).show();
    }
}

public boolean getMobileDataState()
{
    try
    {
        TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");

        if (null != getMobileDataEnabledMethod)
        {
            boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);

            return mobileDataEnabled;
        }
    }
    catch (Exception ex)
    {
       // Log.e(TAG, "Error getting mobile data state", ex);
        Context context = getApplicationContext();
        Toast.makeText(context, "Error getting mobile data state", Toast.LENGTH_LONG).show();
    }

    return false;
}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    imageView = (ImageView) findViewById(R.id.coverSpin);
    Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.welcome_animation);
    imageView.setAnimation(animation);

    getMobileDataState();
    setMobileDataState(true);
 ........................................

This is the first Activity from my app, it is a "welcome" animation activity, where I would like to check if data is on, then app runs normally further, if not, give the user the possibility to enable data, if, when (from settings) the user returns with data disabled then the app does not continue and exits ...

Thank you for your time and understanding (for my no-skills and problem). Any help is appreciated !!!

I would like to say THANK YOU to : vidulaJ and Jagadesha NH . Combining the two solutions from them I succeded in acomplishing the task. I posted the solution that I used, just in case anyone else needs it. vidulaJ and Jagadesha NH thank you, again !

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import java.lang.reflect.Method;

public class WelcomeActivity extends AppCompatActivity {
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    imageView = (ImageView) findViewById(R.id.coverSpin);
    Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.welcome_animation);
    imageView.setAnimation(animation);

    if(isMobileDataEnabled()){

        //Mobile data is enabled and do whatever you want here
        Toast.makeText(this, getString(R.string.sDataOKEnable), Toast.LENGTH_SHORT).show();

}


    else{
        //Mobile data is disabled here
        new AlertDialog.Builder(this).setTitle(getString(R.string.sDataReqMes))
                .setMessage(getString(R.string.sDataReqEnable)).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // if user clicks ok then it will open network settings
                startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            }
        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        }).show();
    }}


private boolean isMobileDataEnabled(){
    boolean mobileDataEnabled = false;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        Class cmClass = Class.forName(cm.getClass().getName());
        Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
        method.setAccessible(true);

        mobileDataEnabled = (Boolean)method.invoke(cm);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mobileDataEnabled;
}

}

I could still use some help in openning the data enable/disable activity/menu directly and not the general settings activity ...


Solution

  • Try this.

    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.animation.Animation;
    import android.view.animation.AnimationUtils;
    import android.widget.ImageView;
    
    import java.lang.reflect.Method;
    
    public class WelcomeActivity extends AppCompatActivity{
    
        private ImageView imageView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_welcome);
    
            imageView = (ImageView) findViewById(R.id.coverSpin);
            Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.welcome_animation);
            imageView.setAnimation(animation);
    
            if(isMobileDataEnabled()){
                //Mobile data is enabled and do whatever you want here
            }
            else{
                //Mobile data is disabled here
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Error");
                builder.setMessage("No mobile data connection detected.");
                builder.setCancelable(false);
    
                builder.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();               
            }
        }
    
        private boolean isMobileDataEnabled(){
            boolean mobileDataEnabled = false;
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            try {
                Class cmClass = Class.forName(cm.getClass().getName());
                Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
                method.setAccessible(true);
    
                mobileDataEnabled = (Boolean)method.invoke(cm);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return mobileDataEnabled;
        }
    
    }