1

我无法让 onServiceConnected() 方法运行,这意味着它没有将我的活动绑定到服务。

这可能是我错过了一些简单的事情 - 但我已经尝试了很多次 - 从头开始​​。

开始了...

我的服务等级

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class QuickService extends Service {

private final IBinder mBinder = new QuickBinder(this);

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

}

我的活页夹类

import android.os.Binder;

public class QuickBinder extends Binder {

private final QuickService service;

public QuickBinder(QuickService service){
    this.service = service;
}

public QuickService getService(){
    return service;
}

}

而且... Activity 试图绑定到服务。

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;

public class QuickActivity extends Activity {

QuickService mService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connecting);
}

@Override
protected void onStart() {
    super.onStart();
    Intent intent = new Intent(this, QuickService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
        unbindService(mConnection);
    }

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        Logger.d("Connected!!! :D");
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        QuickBinder binder = (QuickBinder) service;
        mService = binder.getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
    }
};
}

此外,清单文件中定义的服务 - 如果您认为这是问题所在。

<service android:name=".QuickService"></service>

那么,我在这里做错了什么?为什么不调用 onServiceConnected() 方法?

4

2 回答 2

1

使用以下更新它

 <service android:name=".QuickService">
            <intent-filter>
                <action android:name=".QuickService .BIND" />
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>
于 2012-07-07T05:25:38.117 回答
-1

而不是写:

Intent intent = new Intent(this, QuickService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

你可以写:

startService(new Intent(QuickActivity.this, QuickService.class));

你想在哪里开始服务。

希望这会帮助你。

于 2012-07-07T05:36:41.960 回答