java - Android服务未绑定(bind)

标签 java android service

@Override
protected void onStart(){
    super.onStart();
    Intent musicIntent = new Intent( this, MusicService.class );
    startService(musicIntent);
    getApplicationContext().bindService( musicIntent, mConnection, BIND_AUTO_CREATE);
}

private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mBound = false;
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mBound = true;
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        Log.d(TAG, "Bound");
    }
};

当我启动一个新 Activity 时,我也想启动一个服务并绑定(bind)它,以便我可以使用该服务的一些方法。在 onStart() 方法中,我启动了服务并尝试绑定(bind)它。正如你所看到的,当它被绑定(bind)时,它会在 LogCat 中向我显示。然而,它永远不会!

服务本身将始终被创建和启动(我在这两个方法中都放置了 Log.d(..) )。

list 文件:

<service android:name="com.ppp.p.MusicService"></service>

出了什么问题?

编辑:

@Override
public IBinder onBind(Intent intent) {
    return null;
}

最佳答案

问题出在 onBind() 方法中。为了绑定(bind)到服务,您需要在那里返回一个绑定(bind)器实例(不是 null),如 described here .

public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

}

关于java - Android服务未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24597277/

相关文章:

java - 从字符串创建映射的通用 java 函数

java - web.xml 过滤器映射不转发到 struts

android - 在Android下使用Delphi在TWebbrowser中全屏观看youtube或其他视频时出现问题

android - 日期选择器对话框

android - hdpi ldpi mdpi 图标/菜单分辨率

tomcat - 从命令行将 java_opts 设置为 tomcat 服务

java - OpenShift:在 java 运行时更改 ConfigMap

java - JAVA 污染源

android - 处理三星 SPCM killer

javascript - javamail.setFrom() 在我的 spring 项目中不起作用