2016-09-14 19 views
-1

我正在構建我正在使用位置的Android應用程序。我的位置在服務中實施。當用戶登錄時,如果他沒有打開GPS,他會收到警報對話框。但是當我註銷並再次來到LoginActivity(我的LAUNCHER活動是MainActivity,並且這個GPS的功能是在MainActivity中的onCreate方法)我的應用程序崩潰。 這是我的函數:爲什麼警報會得到這個錯誤?

public void alertForEnablingGPS(){ 
     LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE); 
     if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
       !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
      // Build the alertForEnablingGPS dialog 
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
      builder.setTitle("Location Services Not Active"); 
      builder.setMessage("Please enable Location Services and GPS"); 
      builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialogInterface, int i) { 
        // Show location settings when the user acknowledges the alertForEnablingGPS dialog 
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivity(intent); 
       } 
      }); 
      Dialog alertDialog = builder.create(); 
      alertDialog.setCanceledOnTouchOutside(false); 
      alertDialog.show(); 
     }} 

這是我的錯誤:

09-14 14:19:43.680 7188-7188/com.telnet.asp E/AndroidRuntime: FATAL EXCEPTION: main 
                  java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread. 
                   at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:114) 
                   at android.os.Handler.handleCallback(Handler.java) 
                   at android.os.Handler.dispatchMessage(Handler.java) 
                   at android.os.Looper.loop(Looper.java) 
                   at android.app.ActivityThread.main(ActivityThread.java) 
                   at java.lang.reflect.Method.invokeNative(Native Method) 
                   at java.lang.reflect.Method.invoke(Method.java:525) 
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java) 
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java) 
                   at dalvik.system.NativeStart.main(Native Method) 
                  Caused by: rx.exceptions.OnCompletedFailedException: Unable to add window -- token [email protected] is not valid; is your activity running? 
                   at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:90) 
                   at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:284) 
                   at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:219) 
                   at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107) 
                   at android.os.Handler.handleCallback(Handler.java)  
                   at android.os.Handler.dispatchMessage(Handler.java)  
                   at android.os.Looper.loop(Looper.java)  
                   at android.app.ActivityThread.main(ActivityThread.java)  
                   at java.lang.reflect.Method.invokeNative(Native Method)  
                   at java.lang.reflect.Method.invoke(Method.java:525)  
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)  
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)  
                   at dalvik.system.NativeStart.main(Native Method)  
                  Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token [email protected] is not valid; is your activity running? 
                   at android.view.ViewRootImpl.setView(ViewRootImpl.java) 
                   at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java) 
                   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java) 
                   at android.app.Dialog.show(Dialog.java) 
                   at com.telnet.asp.presentation.view.activities.MainActivity.alertForEnablingGPS(MainActivity.java:385) 
                   at com.telnet.asp.presentation.view.activities.MainActivity.viewAccount(MainActivity.java:142) 
                   at com.telnet.asp.presentation.presenter.AccountPresenter.showAccountInView(AccountPresenter.java:44) 
                   at com.telnet.asp.presentation.presenter.AccountPresenter.access$000(AccountPresenter.java:15) 
                   at com.telnet.asp.presentation.presenter.AccountPresenter$AccountSubscriber.onCompleted(AccountPresenter.java:66) 
                   at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:84) 
                   at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:284)  
                   at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:219)  
                   at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107)  
                   at android.os.Handler.handleCallback(Handler.java)  
                   at android.os.Handler.dispatchMessage(Handler.java)  
                   at android.os.Looper.loop(Looper.java)  
                   at android.app.ActivityThread.main(ActivityThread.java)  
                   at java.lang.reflect.Method.invokeNative(Native Method)  
                   at java.lang.reflect.Method.invoke(Method.java:525) 

我應該怎麼做才能解決這個問題? 在此先感謝。

編輯:當我使用如是的回答我得到這個錯誤:

09-14 15:03:11.346 10896-10896/com.telnet.asp E/WindowManager: Activity com.telnet.asp.presentation.view.activities.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42defcf8 V.E..... R.....ID 0,0-720,351} that was originally added here 
                   android.view.WindowLeaked: Activity com.telnet.asp.presentation.view.activities.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42defcf8 V.E..... R.....ID 0,0-720,351} that was originally added here 
                    at android.view.ViewRootImpl.<init>(ViewRootImpl.java) 
                    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java) 
                    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java) 
                    at android.app.Dialog.show(Dialog.java) 
                    at com.telnet.asp.presentation.view.activities.MainActivity.alertForEnablingGPS(MainActivity.java:392) 
                    at com.telnet.asp.presentation.view.activities.MainActivity.viewAccount(MainActivity.java:143) 
                    at com.telnet.asp.presentation.presenter.AccountPresenter.showAccountInView(AccountPresenter.java:44) 
                    at com.telnet.asp.presentation.presenter.AccountPresenter.access$000(AccountPresenter.java:15) 
                    at com.telnet.asp.presentation.presenter.AccountPresenter$AccountSubscriber.onCompleted(AccountPresenter.java:66) 
                    at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:84) 
                    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:284) 
                    at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:219) 
                    at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107) 
                    at android.os.Handler.handleCallback(Handler.java) 
                    at android.os.Handler.dispatchMessage(Handler.java) 
                    at android.os.Looper.loop(Looper.java) 
                    at android.app.ActivityThread.main(ActivityThread.java) 
                    at java.lang.reflect.Method.invokeNative(Native Method) 
                    at java.lang.reflect.Method.invoke(Method.java:525) 
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java) 
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java) 
                    at dalvik.system.NativeStart.main(Native Method) 
+0

在試試這個你活動,同時顯示對話框, 'if(!isFinishing()) { alert.show(); }' – rushi

+0

嘿,嘗試在** MainActivity **延遲一段時間後顯示對話框。崩潰報告顯示與上下文引用有關的一些問題,但是在您的代碼中,您已經以正確的方式編寫了它。所以試着在使用Handler延遲一段時間後調用這個函數。 –

+0

我編輯了問題,請看看。 – Atenica

回答

-1
import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 

public class GPSTracker extends Service implements LocationListener{ 

    private final Context context; 

    boolean isGPSEnabled= false; 
    boolean isNetworkEnabled= false; 
    boolean canGetLocation= false; 

    Location location; 

    double latitude; 
    double longitude; 

    private static final long MIN_DISTANCE_UPDATES_FOR_CHANGE = 10; 
    private static final long MIN_TIME_BW_UPDATES= 1000*60*1; 

    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.context= context; 
     getLocation(); 
    } 

    public Location getLocation(){ 
     try{ 

      locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE); 

      isGPSEnabled= locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
      isNetworkEnabled= locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if(!isGPSEnabled && !isNetworkEnabled){ 
       //showSettingsAlert(); 
      }else{ 
       this.canGetLocation= true; 

       if(isNetworkEnabled){ 
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_UPDATES_FOR_CHANGE, this); 
       } 
       if(locationManager!= null){ 
        location= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

        if(location !=null){ 
         latitude= location.getLatitude(); 
         longitude= location.getLongitude(); 

        } 
       } 
      } 

      if(isGPSEnabled){ 
       if(location==null){ 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_UPDATES_FOR_CHANGE, this); 

        if(locationManager !=null){ 
         location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

         if(location !=null){ 
          latitude= location.getLatitude(); 
          longitude= location.getLongitude(); 
         } 
        } 
       } 
      } 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     return location; 
    } 

    public void stopUsingGPS(){ 
     if(locationManager !=null){ 
      locationManager.removeUpdates(GPSTracker.this); 
      } 
    } 

    public double getLatitude(){ 
     if(location !=null){ 
      latitude= location.getLatitude(); 
     } 
     return latitude; 
    } 

    public double getLongitude(){ 
     if(location !=null){ 
      longitude= location.getLongitude(); 
     } 
     return longitude; 
    } 

    public boolean canGetLocation(){ 
     return this.canGetLocation; 
    } 

    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog= new AlertDialog.Builder(context); 
     alertDialog.setTitle("GPS is settings"); 
     alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       context.startActivity(intent); 
      } 
     }); 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 

      } 
     }); 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

} 

把這個單獨的類和要使用初始化這個類的對象,並寫上這行代碼你登錄活動。試試這個,讓我知道。

GPSTracker gps; 
gps= new GPSTracker(this); 
if (gps.canGetLocation()) { 
        gps= new GPSTracker(Activity.this); 
        latitude = gps.getLatitude(); 
        longitude = gps.getLongitude();     
       }else{ 
        gps.showSettingsAlert(); 
       } 
+0

你試過這個嗎? –

+0

是的,我再次得到這個錯誤。 – Atenica

+0

等待在另一條評論中爲您發送另一個解決方案。 –