我通过这种方式绑定(bind)到服务:
Activity 类:
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
,但 bundle 为 null
一般服务工作正常。但是,我只需要从应用程序的主要 Activity 中调用 StartListenLocation();
(我决定通过发送标志来执行此操作)。
我如何向服务发送数据?或者还有其他方法可以检查 onBind
启动了什么 Activity ?
最佳答案
你可以通过这种简单的方式传递参数:-
Intent serviceIntent = new Intent(this,ListenLocationService.class);
serviceIntent.putExtra("From", "Main");
startService(serviceIntent);
并在服务类的 onStart 方法中获取参数
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
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();
}
}
享受:)
关于Android:将参数从Activity传递给Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9954878/