我是用以下方式绑定服务的:
活动类:
ListenLocationService mService;
@Override
public void onCreate(Bundle savedInstanceState) {
...
Intent intent = new Intent(this, ListenLocationService.class);
intent.putExtra("From", "Main");
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
...
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName arg0) {
}
};
这是我Service的onBind
方法:
@Override
public IBinder onBind(Intent intent) {
Bundle extras = intent.getExtras();
if(extras == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
String from = (String) extras.get("From");
if(from.equalsIgnoreCase("Main"))
StartListenLocation();
}
return mBinder;
}
我在 LogCat
中看到 "null",尽管我已经在 bindService
之前使用了 intent.putExtra
。总的来说,服务是正常工作的。然而,我只需要从应用程序的主活动中调用 StartListenLocation();
(我决定通过发送一个标志来实现这一点)。
我该如何向服务发送数据?或者也许有另一种方法可以检查启动 onBind
的活动是什么?
onStart
已被弃用,请使用onStartCommand
代替。 - Konstantin Konopko