Pass Data from Activity to Service Using an Intent

Pass data from Activity to Service using an Intent

First Context (can be Activity/Service etc)

For Service, you need to override onStartCommand there you have direct access to intent:

Override
public int onStartCommand(Intent intent, int flags, int startId) {

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

New Context (can be Activity/Service etc)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

Android- How to send data from activity to service?

Here:

 Intent serviceIntent = new Intent(bgservice.class.getName());

Passing String to Intent constructor for creating Intent to start Service. Intent constructor takes String as a Action name which we have added in AndroidManifest.xml.

<service android:enabled="true" android:name=".bgservice">
<intent-filter >
<action android:name="com.microapple.googleplace.bgservice" />
</intent-filter>
</service>

Now use com.microapple.googleplace.bgservice as action name to create Intent:

      Intent serviceIntent = new Intent("com.microapple.googleplace.bgservice");
serviceIntent.putExtra("UserID", "123456");
this.startService(serviceIntent);

OR

Use Intent constrictor which takes Context as first parameter and component name which we want to start as second parameter :

  Intent serviceIntent = new Intent(this,bgservice.class);
serviceIntent.putExtra("UserID", "123456");
this.startService(serviceIntent);

And also use same key which using to add data in Intent currently adding value with UserID key but trying to get value using userID key

How to pass value from Activity to a Service in Android?

You cannot create an object like that from your service. I think you are new to Java. When you do CheckActivity check = new CheckActivity() a new instance of your CheckActivity is created and no doubt it will return zero. Also you should never try creating objects of activities like this in android.

As far as your question is concerned you can pass your editText value to your service via a broadcast receiver.

Have a look at this.

Also if you have the editText value before creating the service you can simply pass it as intent extra , else you can use the broadcast approach.

In your service

broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("getting_data")) {
intent.getStringExtra("value")
}
}
};

IntentFilter intentFilter = new IntentFilter();
// set the custom action
intentFilter.addAction("getting_data"); //Action is just a string used to identify the receiver as there can be many in your app so it helps deciding which receiver should receive the intent.
// register the receiver
registerReceiver(broadcastReceiver, intentFilter);

In your activity

Intent broadcast1 = new Intent("getting_data");
broadcast.putExtra("value", editext.getText()+"");
sendBroadcast(broadcast1);

Also declare your receiver in onCreate of activity and unregeister it in onDestroy

unregisterReceiver(broadcastReceiver);

How to pass data from activity to service while starting service?

You have to Override onStart Method in your service.OnStart method you can get intent of Activity.
If you want to pass ArrayList from activity to service,you can convert your arraylist to array.

In you Activity

Intent intent=new Intent(ServicesActivity.this,FileManagerRequest.class);         
Bundle b=new Bundle()
b.putStringArray("Array", your_array)
intent.putExtras(b);
startService(intent);

in you service

public void onStart(Intent intent, int startid){
super.onStart(intent, startid);
Bundle b=intent.getExtras();
String[] Array = b.getStringArray("Array");
}

How do I pass data between Activities in Android application?

The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

Access that intent on next activity:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");

The docs for Intents has more information (look at the section titled "Extras").

How to pass data from activity to service?

String username = userName.getText().toString(); is already not null? Did you check it?
My solution is:

  • Declare username at the beginning after the class (local variable of the class)
  • You can also create a class to save data as:
public class Common {
public static String username;
}

In MainActivity.java

Comon.username = userName.getText().toString();

After get value of username in Services.java with:

String username= Common.username

Passing data from activity to service through interface


Passing data from activity to service through interface

For getting data from Activity to service using interface we need to get interface object in Actvity which we are implementing in Service.

For example just for testing:

1. Create a static reference in Service:

public static SubscribeHandler subscribeHandler;

2. In onStartCommand() method of Service assign this to subscribeHandler:

subscribeHandler=this;

Now after starting Service access subscribeHandler in Activity from Service for sending data:

subscribeHandler.handleSubscribe("Message");

But not good approach use static objects for sending data between to components of application

So for communicating between Service and Activity use LocalBroadcastManager

How to use LocalBroadcastManager?

Sending data from activity to service UPDATED

To get the number of items, you need to establish a communication between the Activity and Service. For this, you need to implement the Messenger.

Messenger allows for the implementation of message-based communication across processes by help of Handlers.

Handler is a that allows you to send and process these messages.

Steps for implementing a Messenger:

  1. Service implements a Handler which receives the callbacks from the Activity

  2. The Handler then creates a Messenger object which further on creates an IBinder that the Service returns to the Activity.

  3. Activity then uses the IBinder to instantiate the Messenger, which the Activity uses to send messages to the Service.

  4. The Service receives the messages in the Handler created in the 1st step.

Lets now understand it with an example:

Create a Handler in the Service like this:

class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
default:
super.handleMessage(msg);
}
}
}

Now, add the Messenger object along with onBind() method to the Service as mentioned in 2nd step above:

final Messenger messenger = new Messenger(new ServiceHandler());

@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}

In the Activity, we will create a ServiceConnection to fetch the iBinder from the Service to instantiate the Messenger object as mentioned in the 3rd step above.

Messenger messenger;
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder iBinder) {
messenger = new Messenger(iBinder);
}

public void onServiceDisconnected(ComponentName className) {
}
};

Bind the Service to the Activity by help of the ServiceConnection created above:

bindService(new Intent(this, MessengerService.class), serviceConnection,
Context.BIND_AUTO_CREATE);

To send messages to the Service from the Activity, use the send() method of the Messenger object.

If you want to receive messages from the Service in the Activity, you need to create a Messenger in the Activity along with a Handler and use the replyTo parameter of the Messenger to receive messages to the respective Handler.

Updated Answer:

To send Message via Messenger do this:

  1. Create a Bundle object.

  2. Put data into the Bundle Object.

  3. Add the bundle object to the Message object.

  4. Send Message object to Service by help of Messenger object.

Example:

Bundle bundle = new Bundle();
bundle.putFloat("key", 1.0f);
Message message = Message.obtain();
message.setData(bundle);
messenger.send(message);

For more info, visit the following link:

http://developer.android.com/guide/components/bound-services.html

How to pass data from Activity to Service without starting a new instance?

Solved!
I checked and if I did

public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.d(TAG,"super called "+startId);
...

I saw startId was constantly increasing and giving timeouts eventually. Solved by calling

stopService(intent)
...
startService(intent)

so simple and yet so many headaches to find it out!



Related Topics



Leave a reply



Submit