2016-09-14 2 views
-1

Я создаю приложение для Android, где я использую местоположения. Мои местоположения реализованы на службе. И когда пользователь входит в систему, он получает предупреждение, если он не включил GPS. Но когда я выхожу из системы и снова прихожу к LoginActivity (моя активность LAUNCHER - MainActivity, и эта функция для GPS находится в методе onCreate в MainActivity), мое приложение падает. Это моя функция:Почему предупреждение получает эту ошибку?

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) 

Что я должен сделать, чтобы исправить это? Спасибо заранее.

EDIT: когда я использую ответ Rushi, я получаю эту ошибку:

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

, ожидая отправки другого решения для этого в другом комментарии. –