Ошибка при отвязке Service

388
10 ноября 2017, 07:42

Есть Activity которое делает привязку Service.

public class MainActivity extends MvpAppCompatActivity implements ServiceConnection{
    public static final String TAG = MainActivity.class.getSimpleName();

    private WebsocketService.LocalBinder binder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        /*
        * Bind websocket service
        * */
        getApplicationContext().bindService(new Intent(this, WebsocketService.class), this, Context.BIND_AUTO_CREATE);
    }
    @Override
    protected void onPause() {
           /*
        * Bind websocket service
        * */
        getApplicationContext().unbindService(this);
        super.onPause();
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.d(TAG, "onServiceConnected() called with: componentName = [" + componentName + "], iBinder = [" + iBinder + "]");
        binder = (WebsocketService.LocalBinder) iBinder;
        //add websocket listener
        binder.getService().addListener(s -> Log.d(TAG, "onMessage() called with: s = [" + s + "]"));
    }
    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.d(TAG, "onServiceDisconnected() called with: componentName = [" + componentName + "]");
        binder.closeWebsocket();
    }
}

При сворачивании приложения я получаю ошибку:

java.lang.RuntimeException: Unable to pause activity {org.common/org.common.ui.activity.MainActivity}: java.lang.IllegalArgumentException: Service not registered: org.common.ui.activity.MainActivity@f7c7c68 at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3976) at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3942) at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3916) at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3890) at android.app.ActivityThread.-wrap15(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Caused by: java.lang.IllegalArgumentException: Service not registered: org.common.ui.activity.MainActivity@f7c7c68 at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1466) at android.app.ContextImpl.unbindService(ContextImpl.java:1622) at android.content.ContextWrapper.unbindService(ContextWrapper.java:697) at org.common.ui.activity.MainActivity.onPause(MainActivity.java:155) at android.app.Activity.performPause(Activity.java:7115) at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1407) at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3965) at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3942)  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3916)  at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3890)  at android.app.ActivityThread.-wrap15(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Answer 1

Внес следующие изминения в код, после чего указаная в вопрос ошибка была устранена:

@Override
protected void onResume() {
    Log.wtf(TAG, "onResume() called");
    /*
    * Bind websocket service
    * */
    if (!attemptingToBind) {
        attemptingToBind = true;
        getApplicationContext().bindService(new Intent(this, WebsocketService.class), this, Context.BIND_AUTO_CREATE);
    }
    super.onResume();
}
@Override
protected void onPause() {
    Log.wtf(TAG, "onPause() called");
       /*
    * Bind websocket service
    * */
    attemptingToBind = false;
    if (bound) {
        getApplicationContext().unbindService(this);
        bound = false;
    }
    super.onPause();
}

// SERVICE CONNECTION
private boolean attemptingToBind = false;
private boolean bound = false;
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    Log.wtf(TAG, "onServiceConnected() called with: componentName = [" + componentName + "], iBinder = [" + iBinder + "]");
    attemptingToBind = false;
    bound = true;
    binder = (WebsocketService.LocalBinder) iBinder;
    //add websocket listener
    binder.getService().addListener(s -> Log.d(TAG, "onMessage() called with: s = [" + s + "]"));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
    Log.wtf(TAG, "onServiceDisconnected() called with: componentName = [" + componentName + "]");
    attemptingToBind = false;
    if (bound) {
        getApplicationContext().unbindService(this);
        bound = false;
    }
}
READ ALSO
Синтаксис Java: “->”

Синтаксис Java: “->”

Что обозначает это выражение?

362
Клонирование Object'ов с модификатором final

Клонирование Object'ов с модификатором final

Будет ли final клон другого final объектаКлонирование реализовано с помощю интерфейса Clonable

287
Как записать данные в файл с консоли

Как записать данные в файл с консоли

Мне надо создать метод, который будет записывать все содержимое введенное пользователем с консоли в файл по заданному пути, не перезаписывая...

322