gpt4 book ai didi

android - 如何在服务中获取 Intent?

转载 作者:搜寻专家 更新时间:2023-11-01 08:27:38 26 4
gpt4 key购买 nike

我有这个 Intent :

Intent serviceIntent = new Intent(getApplicationContext(), Servicio.class);
serviceIntent.putExtra(MainActivity.EXTRA_BT_DEVICE, btDevice);
getApplicationContext().startService(serviceIntent);

但由于某种原因,在具有此代码的服务中:

btDevice = (BluetoothDevice) params.getExtras().get(MainActivity.EXTRA_BT_DEVICE); 
// btDevice = getParcelableExtra(EXTRA_BT_DEVICE)

它说 Intent 是空的,但它在 Activity 上不是空的。

最佳答案

您需要将服务绑定(bind)到 Activity 以访问服务方法。使用服务对象,您可以调用服务方法并将值从 Activity 传递到服务。把这段代码写在activity-

 Servicio mService;

@Override
protected void onResume() {
super.onResume();
Intent bindIntent = new Intent(this, Servicio.class);
bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

}
@Override
protected void onPause() {
super.onPause();

unbindService(mServiceConnection);
mService = null;
}

private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
mService = ((Servicio.LocalBinder) rawBinder).getService();

}

public void onServiceDisconnected(ComponentName classname) {
//// mService.disconnect(mDevice);
mService = null;
}
};

mService 是您的服务类的对象,使用它您可以将值传递给服务。

写在服务类中

private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public Servicio getService() {
return Servicio.this;
}
}

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

关于android - 如何在服务中获取 Intent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43272512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com