Android- How to send data from service to activity?

Android- How to send data from service to activity?

Recently, I needed send data from background service to activity. I couldn’t find any decent examples on the web or StackOverflow, so I decided to put one together.

 I really like when someone has a complete working sample, so I will provide that as well you can refer source code at this article.

The Android project is very simple, with just two classes, the activity and the background service. We’ll take a look first at the background service.

  1. MainActivity.java -- Activity
  2. PhoneStateReceiver.java -- Background Service
MainActivity.java

public class MainActivity extends Activity {

    Context context;
    BroadcastReceiver updateUIReciver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        IntentFilter filter = new IntentFilter();
        filter.addAction("service.to.activity.transfer");
        updateUIReciver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //UI update here
                if (intent != null)
                    Toast.makeText(context, intent.getStringExtra("number").toString(), Toast.LENGTH_LONG).show();
            }
        };
        registerReceiver(updateUIReciver, filter);
    }
}

Make sure BroadcastReceiver must be registered and also unregistered on OnPause().


PhoneStateReceiver.java

public class PhoneStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            System.out.println("Receiver start");
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                Intent local = new Intent();
                local.setAction("service.to.activity.transfer");
                local.putExtra("number", incomingNumber);
                context.sendBroadcast(local);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


I hope this post is useful to you. kindly share your feedback as comment here.

Thanks for reading this article.

Ma Sha Allah, thank you!

回复

I don't see any background services here. No extends of Service here

Osman Khalid

Associate Professor, Department of Computer Science, COMSATS University Islamabad, Abbottabad Campus

6 年

You are deriving from "Service" class in above example. Are you using a system service or so?

回复
Lucian R.

Software Engineer at GoDaddy

6 年

Many thanks, very useful!

要查看或添加评论,请登录

Mahesh Gavale的更多文章

社区洞察

其他会员也浏览了