Alberto Martínez
Alberto Martínez

Reputation: 251

How can I get Intent in a service?

I have this intent:

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

But for some reason, in the service with this code:

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

It says the intent is null, but it isn't null on the activity.

Upvotes: 2

Views: 1177

Answers (1)

Hitesh Gehlot
Hitesh Gehlot

Reputation: 1347

You need to bind service to activity for access service methods. Using service object you can call service method and pass value from activity to service. Write this code in 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 is the object of your service class using this you can pass value to service.

Write this in service class

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

Upvotes: 2

Related Questions