Android- How to send data from service to activity?
Mahesh Gavale
Mobile App Developer || Android || Kotlin || Flutter || iOS-Swift || Fintech || Digital Banking
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.
- MainActivity.java -- Activity
- 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.
--
1 年Ma Sha Allah, thank you!
Software Developer
6 年I don't see any background services here. No extends of Service here
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?
Software Engineer at GoDaddy
6 年Many thanks, very useful!