Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.Context;

import android.net.ConnectivityManager;

import android.os.Build;

import android.telephony.TelephonyManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    /**
     * Requires {@link android.Manifest.permission#READ_PHONE_STATE} permission.
     *
     * @param context
     * @return
     */
    public static boolean isMobileDataEnabled(Context context) {
        boolean mobileDataEnabled = false; // Assume disabled

        if (Build.VERSION.SDK_INT >= 21) {
            try {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                Class<?> tmClass = Class.forName(tm.getClass().getName());
                Method method = tmClass.getDeclaredMethod("getDataEnabled");
                method.setAccessible(true);
                mobileDataEnabled = (Boolean) method.invoke(tm);
            } catch (ClassNotFoundException | NoSuchMethodException | IllegalArgumentException
                    | IllegalAccessException | InvocationTargetException ex) {
                ex.printStackTrace();
            }
        } else {
            try {
                ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                Class<?> cmClass = Class.forName(cm.getClass().getName());
                Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
                method.setAccessible(true);
                mobileDataEnabled = (Boolean) method.invoke(cm);
            } catch (ClassNotFoundException | NoSuchMethodException | IllegalArgumentException
                    | IllegalAccessException | InvocationTargetException ex) {
                ex.printStackTrace();
            }
        }

        return mobileDataEnabled;
    }
}