Java AlertDialog是否要检查系统服务?

Java AlertDialog是否要检查系统服务?,java,android,gps,android-alertdialog,application-settings,Java,Android,Gps,Android Alertdialog,Application Settings,快速提问,我有一个方法,其中建立了一个警报对话框,并希望在它检测到android设备上的WIFI或GPS未启用时调用它 因此,本质上: 如果:设备没有wifi或GPS//不知道此代码是如何产生的 { 生成警报对话框 } 其他: { 别担心,什么都不要做 } 有什么想法吗 我的代码: public void checkPhoneStatus(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

快速提问,我有一个方法,其中建立了一个警报对话框,并希望在它检测到android设备上的WIFI或GPS未启用时调用它

因此,本质上:

如果:设备没有wifi或GPS//不知道此代码是如何产生的 { 生成警报对话框 } 其他: { 别担心,什么都不要做 }

有什么想法吗

我的代码:

 public void checkPhoneStatus(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setTitle("Warning");
        alertDialog.setMessage("We've noticed your WIFI and GPS are off. Are you okay? Do you want to call the Authorities?");
        alertDialog.setIcon(R.drawable.about);
        alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent callIntent = new Intent(Intent.ACTION_CALL); //Runs the intent - starts the phone call
                callIntent.setData(Uri.parse("tel:77777777")); //Number set for the phone call
                startActivity(callIntent); //Start the intent
            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), "Please go to Settings and enable WIFI or GPS!",
                        Toast.LENGTH_SHORT).show();
            }
        });
        alertDialog.show();
    }

这个设计听起来不精确

我要做的是:

我有一个后台流程,检查互联网/wifi是否每n秒发出一次ping;n=120

2如果ping失败,则显示对话框

并且只在您知道要显示对话框之前构建对话框


您需要将业务逻辑与ui分离;它带来了更干净的设计。

您可以使用它来检查WiFi是否已启用:

public boolean isWiFiEnabled(Context context) {
     WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
     return wifi.isWifiEnabled();
}
要检查是否启用了GPS,您可以使用:

public boolean isGPSEnabled (Context context){
     LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
     return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
编辑:我会这样使用它:

if (!isWiFiEnabled(this) || !isGPSEnabled(this)) {
    displayConnectivityProblemDialog();
}

请注意,我已将checkPhoneStatus方法重命名为displayConnectivityProblemDialog。没有必要,但只是一个品味问题:

你能告诉我如何使用我的代码吗,我的IF/ELSE语句给我带来了一些问题……编辑了这篇文章,以包含一个示例用法:我最初想这样做,但不确定如何继续,所以只需简单检查一下它是否被启用/禁用就足够了。你能告诉我这将如何工作或链接?