如何强制onServiceDisconnected()得到调用?

Din*_*ino 4 service android

通过调用绑定服务后:

bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)

我需要进行调试,以便调用onServiceDisconnected().

我知道Android系统在与服务的连接意外丢失时调用此方法,例如当服务崩溃或被杀死时,以及在客户端解除绑定时未调用此服务.

所以我的问题是如何在我想要的时候强制onServiceDisconnected()调用,这样我就可以完成测试了?

ken*_*ota 6

您需要启动服务然后使用Context.BIND_NOT_FOREGROUND标志绑定,然后将其停止.这将导致调用onServiceDisconnected.以下是MainActivity的代码(假设您已定义TestService服务),其中两个按钮链接到调用doBind和doUnbind方法:

package com.example.servicetest;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "Service disconnected: " + name);
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "Service connected: " + name);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void doBind(View v) {
        Intent i = new Intent(this, TestService.class);
        startService(i);
        bindService(i, connection, Context.BIND_NOT_FOREGROUND);
    }

    public void doUnbind(View v) {
        Intent i = new Intent(this, TestService.class);
        stopService(i);
    }

}
Run Code Online (Sandbox Code Playgroud)

单击按钮时,此代码提供以下日志:

11-27 09:21:57.326: D/MainActivity(10724): Service connected: ComponentInfo{com.example.servicetest/com.example.servicetest.TestService}
11-27 09:21:58.099: D/MainActivity(10724): Service disconnected: ComponentInfo{com.example.servicetest/com.example.servicetest.TestService}
Run Code Online (Sandbox Code Playgroud)

  • @DinoZarafonitis它使用Context.BIND_NOT_FOREGROUND为我工作,但你*有*调用startService(i); 在那之前.我在答案中包含的代码是提供附加的logcat输出.使用Context.BIND_NOT_FOREGROUND时可能缺少startService,并且您的服务未启动. (2认同)