DEV Community

Damith
Damith

Posted on

Pass Data Between Services and Activities in Android

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

Enter fullscreen mode Exit fullscreen mode

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");

        }
 };

Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

And That's All !

You can also try this vice-versa from activity to service...

Discussion (0)