我无法运行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;
}
}
并且......试图绑定到服务的活动。
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()方法?
答案 0 :(得分:1)
使用以下
更新它 <service android:name=".QuickService">
<intent-filter>
<action android:name=".QuickService .BIND" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
答案 1 :(得分:-1)
而不是写作:
Intent intent = new Intent(this, QuickService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
你可以写:
startService(new Intent(QuickActivity.this, QuickService.class));
您要开始服务的地方。
希望这会对你有所帮助。