Я создаю приложение для 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)
Попробуйте это в вашем активность при показе диалога, 'if (! isFinishing()) { alert.show(); } ' – rushi
Эй, попробуйте отобразить диалог после некоторой задержки на ** MainActivity **. Отчет о сбое показывает некоторую проблему, связанную с ссылкой на контекст, но в коде, который вы написали правильно. Поэтому просто попробуйте вызвать эту функцию после некоторой задержки с помощью Handler. –
Я редактировал вопрос, пожалуйста, посмотрите. – Atenica