当我的活动开始时,它会创建一个充当服务器的服务。服务器从我桌面上的python脚本接收原始数据。该服务创建并维护DataManagers,它在一个键入DM名称的哈希映射中处理来自我的python脚本的所有数据。在任何给定的时间,我都需要一个活动来绑定服务请求来自服务和进程的一些数据,当活动暂停,停止或被销毁时它将解除绑定。
我相信我的绑定是正确的,但是当我启动服务时,传递的ServiceConnection始终返回null。任何想法都在发生什么?我的代码是直接从Android的RemoteService类中窃取的 谢谢 〜Aedon
{Code addendum}
绑定到PublicService的HomeScreen活动
@Override public void onCreate(Bundle icicle) {
super.onCreate(icicle);
doBindService();
setContentView(R.layout.homescreen);
initView();
}
public void initView() {
workbenchs = (Gallery)findViewById(R.id.workbenchs);
workbenchs.setMinimumHeight(h/4);
workbenchs.setAdapter(new WorkBenchAdapter(this));
workbenchs.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent it = new Intent(HomeScreen.this, Controller.class);
it.putExtra("workbench", arg2);
startActivity(it);
}
});
}
// Gallery Adapter
public class WorkBenchAdapter extends BaseAdapter {
public WorkBenchAdapter(Context c) { }
public int getCount() {return mBoundService.getNumBenchs();}
public Object getItem(int position) {return position;}
public long getItemId(int position) {return position;}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(HomeScreen.this);
i.setImageBitmap(mBoundService.getWorkbench(position).toBitmap());
i.setLayoutParams(new Gallery.LayoutParams(w/4, h/4));
return i;
}
}
// Service Necessities
public boolean mIsBound = false;
private PublicService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((PublicService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
void doBindService() {
Log.d(TAG, "Binding...");
bindService(new Intent(this, PublicService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
Log.d(TAG, "Bound.");
}
void doUnbindService() {
if (mIsBound) {
Log.d(TAG, "Unbinding...");
unbindService(mConnection);
mIsBound = false;
Log.d(TAG, "Unbound.");
}
}
我的问题来自Workbench适配器。创建适配器时,它调用get count(从0开始),但它一直说mBoundService为null。我已经尝试在绑定之前启动服务,并且没有任何改变......
答案 0 :(得分:2)
您是否在清单中指定了服务标签?
在<application>
中,您需要像<service android:name="namespace.ServiceName"/>