Android Check GPS State On and Off condition useing Toggle Button?

MainActivity.java

public class MainActivity extends Activity {

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

final ToggleButton tB = (ToggleButton) findViewById(R.id.toggleButton);
tB.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
if (tB.isChecked()) {
// Button is ON
Log.i("", "true");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
} else {
// Button is OFF
Log.i("", "false");
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}
});
}
}

activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/toggleButton1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_marginTop="50dp"
            android:text="ToggleButton" />
    </LinearLayout>

</RelativeLayout>

and give permissions to in  `Androidmanifest.xml ` like this 

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

No comments:

Select DateRange UsingRangePicker.

  /* * This Method is for select range from picker. * */ private fun selectDateRangeUsingRangePicker () { pageNumber = 1 val displ...