Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

How to automatically turn on network in OnCreate?

My app needs internet connection in order to retrieve longitude and latitude. How can I show a popupbox at the beginning of my app if the phone's network is turned off? The popupbox should says something like this:

Your network is disable, enable now?

Under this text a button will be placed, which says "OK", when the user presses this the WiFi or mobile network will be turned on.

Thanks in advance

Upvotes: 0

Views: 243

Answers (1)

jcxavier
jcxavier

Reputation: 2232

You shouldn't automatically turn on the WiFi for your users, and I'm not sure that's even possible with the mobile network.

Here's a sample code which creates an AlertDialog in the end of the onCreate method, and shows it to the user. In case the user wants to enable it he will be forwarded to the Android wireless settings screen, where he can manually enable the WiFi connection.

In case he clicks cancel, the application will quit. However, you can model this behavior to your taste, this is just an example of how I would accomplish this particular task.

@Override
public void onCreate(final Bundle savedInstanceState) {
    // your code

    new AlertDialog.Builder(this)  
       .setMessage("Your network is disabled, enable now?")  
       .setTitle("Alert")  
       .setCancelable(false)
       .setPositiveButton(android.R.string.ok, 
           new DialogInterface.OnClickListener() {  
               public void onClick(DialogInterface dialog, int whichButton) {
                   // launch settings
                   Intent settings = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                   startActivity(settings);
               }  
           })
       .setNegativeButton(android.R.string.cancel,
           new DialogInterface.OnClickListener() {  
               public void onClick(DialogInterface dialog, int whichButton) {
                   dialog.dismiss();

                   // finish activity
                   finish();
               }  
           })
       .show();
}

EDIT:

Just double-checked the Settings intent against the Android Developer documentation (http://developer.android.com/reference/android/provider/Settings.html#ACTION_WIRELESS_SETTINGS), and they advise you that sometimes this Activity may not exist:

Activity Action: Show settings to allow configuration of wireless controls such as Wi-Fi, Bluetooth and Mobile networks. In some cases, a matching Activity may not exist, so ensure you safeguard against this.

Upvotes: 2

Related Questions