1

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 ...

Community
  • 1
  • 1
Robert
  • 123
  • 2
  • 9

3 Answers3

3

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;
    }

}
vidulaJ
  • 1,232
  • 1
  • 16
  • 31
  • Hello. Thank you, I have tried this, and it works but it is incomplete. If data is enabled, the app does it's job, if data disabled exits instanlty (and this is bad because the user doesn't have a clue that he needs to enable data if he wants to use the app). It still needs the second part : telling the user that mobile data must be enabled to be able to use the app, and open the settings to let him do that ... Thank you again. – Robert Oct 20 '16 at 05:02
  • Thank you. I have combined both your solution and the one from Jagadesha NH and it is allmost perfect. Now the general settings are openned when no data is enabled and user wants to permit data, is there a more direct shortcut to the data enable/disable menu ?! Thank you again – Robert Oct 20 '16 at 05:38
  • I guess you can directly enable Mobile data from your code. Let me see that. – vidulaJ Oct 20 '16 at 05:39
  • One more thing : If I start the app, data disabled, but from the Alert Dialog I accept to enable data, I go to settings, I enable data, and when I return to the app, the app it is frozen at the welcome activity, does not go further. Can I restart somehow or continue the app if I enable data ?! – Robert Oct 20 '16 at 05:47
  • You can do that. You got to go to Data Settings page with a Result Code. Refer this. http://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android – vidulaJ Oct 20 '16 at 06:01
  • Thank you, I updated the post/question with the final (for now) solution used. – Robert Oct 20 '16 at 14:21
  • Glad to know. FYI I could provide you the snippet to enable Mobile Data directly. – vidulaJ Oct 20 '16 at 14:32
  • I'm not sure that doing that is totally fair for the user. If he enabled data willingly, ok, if not, he doesn't use the app. But at least he is presented with a choice ... Thank you again – Robert Oct 20 '16 at 14:41
  • Fair enough. If he is informed before turning on Mobile Data it is not that bad feature. – vidulaJ Oct 20 '16 at 14:53
1

Try this simple program, if the data is not on it will alert user to open settings

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!isDataAvailable()) { //check if data is enabled or not
            new AlertDialog.Builder(this).setTitle("Unable to connect")
                    .setMessage("Enable data?").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();
        } else {
            Toast.makeText(this, "DATA IS ON", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isDataAvailable() {
        // returns true or false based on whether data is enabled or not
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
}
Jagadesha NH
  • 2,529
  • 2
  • 23
  • 41
  • Hello, and thank you. Your solution works (partially). But the problem is that no matter that wifi or data, if one of them is enabled, the app runs. I'm interested ONLY in mobile data (gprs or how is it called), regardless of wifi state. Is there a solution for that ? Thank you again – Robert Oct 20 '16 at 05:08
  • I have replaced – Robert Oct 20 '16 at 05:20
  • startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); with Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("com.android.phone","com.android.phone.NetworkSetting"); startActivity(intent); but it opens the available networks tab and not the mobile data settings ... – Robert Oct 20 '16 at 05:21
  • Thank you, I updated the post/question with the final (for now) solution used. I could still use some help in openning the data enable/disable activity/menu directly and not the general settings activity ... – Robert Oct 20 '16 at 14:21
0

Please try this

public boolean isNetworkAvailable(Context context) {
        ConnectivityManager ConnectMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (ConnectMgr == null)
            return false;
        NetworkInfo NetInfo = ConnectMgr.getActiveNetworkInfo();
        if (NetInfo == null)
            return false;

        if (!NetInfo.isConnected()) {
            //Show pop up
        }
    }

Don't forget to add these permission in manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />