How do I see if Wi-Fi is connected on Android?

前端 未结 22 2632
挽巷
挽巷 2020-11-22 05:56

I don\'t want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could sti

22条回答
  •  悲&欢浪女
    2020-11-22 06:30

    You can turn WIFI on if it's not activated as the following 1. check WIFI state as answered by @Jason Knight 2. if not activated, activate it don't forget to add WIFI permission in the manifest file

    
    

    Your Java class should be like that

    public class TestApp extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        //check WIFI activation
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
        if (mWifi.isConnected() == false) {
            showWIFIDisabledAlertToUser();
        }
        else {
            Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }
    }
    
    
    private void showWIFIDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
                .setCancelable(false)
                .setPositiveButton("Goto Settings Page To Enable WIFI",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog, int id){
                                Intent callGPSSettingIntent = new Intent(
                                        Settings.ACTION_WIFI_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int id){
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
    

    }

提交回复
热议问题