Pass Data Between Services and Activities in Android
Damith
Posted on December 7, 2021
Create Runnable Class
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class CommandRunnable implements Runnable{
private static final String TAG = "CommandRunnable";
private Context context;
private String text;
public CommandRunnable(Context _context,String text){
this.context = _context;
this.text= text;
}
@Override
public void run() {
sendMessage(text);
}
private void sendMessage(String msg) {
Intent intent = new Intent("my-message");
intent.putExtra("log-msg", msg);
LocalBroadcastManager.getInstance(context)
.sendBroadcast(intent);
}}
Now Add Listener to your activity
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this)
.registerReceiver(messageReceiver, new IntentFilter("my-message"));
}
private BroadcastReceiver messageReceiver = new
BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String log = intent.getStringExtra("log-msg");
}
};
Now Add Sender to your Service
import android.os.Handler;
public static Handler handler = new Handler();
public static Handler handler = new Handler();
void sendMessage(String msg){
handler.post(new CommandRunnable(this,msg));
}
And That's All !
You can also try this vice-versa from activity to service...
💖 💪 🙅 🚩
Damith
Posted on December 7, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.