Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 我如何在服务中获得意图?_Android - Fatal编程技术网

Android 我如何在服务中获得意图?

Android 我如何在服务中获得意图?,android,Android,我的意图是: Intent serviceIntent = new Intent(getApplicationContext(), Servicio.class); serviceIntent.putExtra(MainActivity.EXTRA_BT_DEVICE, btDevice); getApplicationContext().startService(serviceIntent); 但由于某些原因,在使用此代码的服务中: btDevice = (BluetoothDevice)

我的意图是:

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)

它表示意图为null,但在活动上不是null。

您需要将服务绑定到活动以访问服务方法。使用服务对象,您可以调用服务方法并将值从活动传递给服务。 在活动中编写此代码-

 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;
}

我不想向服务发送值,我只想通过这种方式发送对象您可以发送所有您想要的东西,包括BluetoothDevice它都是红色的,一些变量,我必须在之前创建的库?您确定在activity中编写此代码吗?private ServiceConnection mServiceConnection=new ServiceConnection(){public void onServiceConnected(ComponentName类名称,IBinder rawBinder){mService=((Servicio.LocalBinder)rawBinder).getService();}public void onServiceDisconnected(ComponentName类名称){///mService.disconnect(mDevice);mService=null;}};是的,不管怎样,我想使用我展示给你的代码,这个代码似乎不适用于我的项目