Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show notification from background service?

The project I am working on has two different apps, 1 is server and other is client. Server app has 1 service class, which initiates server thread in onStartCommand() function. Class for server thread is defined in service class itself. Whenever server receives any data from client it stores in the database. So problem is, I want to notify user that new data has been arrived through notification or toast message whichever possible. Also tell me where should I write code for notification, whether I should write in service class or thread class or firstActivity class from which i am starting server service. Thank you.

like image 994
sagar Avatar asked Oct 09 '11 07:10

sagar


People also ask

How do I know if apps are running in the background Android?

To see what apps are running in the background, go to Settings > Developer Options > Running Services.

What does background service being used mean?

What is background data? Background data — also called background app refresh — is the use of mobile data by apps when they're not in active use. If you allow background data usage, apps will constantly update themselves in the background with the newest information and content.


1 Answers

First you need to read this article on how to use Notifications.

Next use this to send a Notification, you can write this code in the service class at the point where you receive some data from the client.

NotificationManager notificationManager =
    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
CharSequence notiText = "Your notification from the service";
long meow = System.currentTimeMillis();

Notification notification = new Notification(icon, notiText, meow);

Context context = getApplicationContext();
CharSequence contentTitle = "Your notification";
CharSequence contentText = "Some data has arrived!";
Intent notificationIntent = new Intent(this, YourActivityThatYouWantToLaunch.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

int SERVER_DATA_RECEIVED = 1;
notificationManager.notify(SERVER_DATA_RECEIVED, notification);
like image 198
Reno Avatar answered Sep 30 '22 13:09

Reno