DEV Community

Damith
Damith

Posted on

3 3

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...

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay