安卓警报对话框没有显示在仿真器上
问题描述:
我写了代码来检查GPS设置并发出警报对话框,但它并未显示在android模拟器中。安卓警报对话框没有显示在仿真器上
这是用于检查GPS设置并显示警报对话框的代码。
package com.example.user.testlocation;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Location extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
}
private void isLocationEnalbled(){
LocationManager locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)|| !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
else{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Confirm Location");
alertDialog.setMessage("Your Location is enabled, please enjoy");
alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
}
}
它没有显示任何错误,但是当我执行它时不显示警告对话框。
答
你永远不会打电话isLocationEnalbled()
做检查的方法。将此添加到您的课程中,以便每次活动resumed时,应用程序都会检查isLocationEnalbled()
。
@Override
public void onResume() {
super.onResume();
isLocationEnalbled();
}
+0
非常感谢,我真的很新的android编程,aha –
答
在onCreate()方法,你必须调用控制的isLocationEnalbled()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
isLocationEnalbled()
}
+0
非常感谢。它确实有很大的帮助 –
流量,Android中的onCreate()方法开始。你需要打电话给'isLocationEnabled()' –