0

I am a beginner in Android, I made a simple app for mobile data off and on using checkbox. now I want to add time scheduler of 1 minute, it means mobile data off and on automatically after every 1 minute. How can you add this functionality to my project?

MainActivity Class-

public class MainActivity extends AppCompatActivity {
    CheckBox mDataStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDataStatus = (CheckBox) findViewById(R.id.checkBox);
        mDataStatus.setChecked(getMobileDataState());

        mDataStatus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked) {
                    try {
                        setMobileDataEnabled(true);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    try {
                        setMobileDataEnabled(false);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    private void setMobileDataEnabled(boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        final ConnectivityManager conman = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class.forName(conman.getClass().getName());
        final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField.get(conman);
        final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);
        setMobileDataEnabledMethod.invoke(connectivityManager, enabled);}

    public boolean getMobileDataState() {
        try {
            TelephonyManager telephonyService = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
            if (null != getMobileDataEnabledMethod) {
                boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);
                return mobileDataEnabled;
            }
        } catch (Exception ex) {
            Log.e("error", "Error getting mobile data state", ex);
        }
        return false;
    }

}

Activity_main.xml-

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android.mobiledataoffon.MainActivity">


    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="119dp"
        android:layout_height="40dp"
        android:text="CheckBox"
        tools:layout_editor_absoluteX="77dp"
        tools:layout_editor_absoluteY="64dp" />
</android.support.constraint.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.mobiledataoffon">
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
FarshidABZ
  • 3,860
  • 4
  • 32
  • 63
  • Exactly what have you tried and what problem are you experiencing in implementing this functionality? I assume you aren't expecting someone to write it for you. – David Nov 21 '17 at 07:31
  • use handler, forget timer task – hemen Nov 21 '17 at 09:07

2 Answers2

1

There is allot of ways to call a timer every X seconds and then running a piece of code every time this timer finish.

it all have pros and cons

one option is opening a timerTask that would run on your main thread (the thread that most of your ui runs on)

here is an example :

https://www.journaldev.com/1050/java-timer-timertask-example

a better option would be to user an alarm manager, here is an example :

https://developer.android.com/training/scheduling/alarms.html

most of the times u can just use a countdown timer here is an example for this:

https://developer.android.com/reference/android/os/CountDownTimer.html

and you can even open processes that run on the background checking intervals, again allot of options.

start with what i brought you here and if you need more options just specify the question a bit better and read some on the matter.

just mind first of that u need to take care of the timer when the screen is not on front , and try to not run it on the main thread.

Chief Madog
  • 1,738
  • 4
  • 28
  • 55
0

If you want to call a function every 1 min , you can use TimerTask and Timer.

     Timer timer = new Timer ();
     TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                //WHAT EVER FUNCTION YOU WANT TO CALL CALL FROM HERE

            }
        };
        timer.scheduleAtFixedRate(timerTask, 0,60* 1000);//this for every 60 seconds

If you want to stop the timer,

     timer.cancel();
     timer.purge();
Saranya Subramanian
  • 417
  • 1
  • 5
  • 19
  • Thanks for your Answer, its really helpful for me, but now i want to cancel my timer on click on another button and start on another, is it possible or not – sandeep sharma Nov 28 '17 at 12:32
  • Make timer as instance variable. So you can access timer variable from anywhere – Saranya Subramanian Nov 28 '17 at 12:36
  • but on btn.setclickonlistner all variable declared as in inner class, we don't create as a instance, we need to start on click on one and stop on another, we can not create timer as a instance – sandeep sharma Nov 28 '17 at 13:00
  • Check this link but why you need to see logs in mobile screen ? You can use logcat right . https://stackoverflow.com/questions/4242765/show-log-messages-on-screen-for-android-application – Saranya Subramanian Nov 29 '17 at 06:48
  • i am making an app to mobile data on and off, so for this i prints logs when data off and on after specific time – sandeep sharma Nov 29 '17 at 07:16