2017-02-11 107 views
0

我寫了代碼來檢查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(); 
      } 
     } 
    } 

它沒有顯示任何錯誤,但是當我執行它時不顯示警告對話框。

+0

流量,Android中的onCreate()方法開始。你需要打電話給'isLocationEnabled()' –

回答

0

你永遠不會打電話isLocationEnalbled()做檢查的方法。將此添加到您的課程中,以便每次活動resumed時,應用程序都會檢查isLocationEnalbled()

@Override 
public void onResume() { 
    super.onResume(); 
    isLocationEnalbled(); 
} 
+0

非常感謝,我真的很新的android編程,aha –

0

在onCreate()方法,你必須調用控制的isLocationEnalbled()

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_location); 
     isLocationEnalbled() 
    } 
+0

非常感謝。它確實有很大的幫助 –