Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an icon in status bar when my task is running

I am creating an android service which will start running after the device boot process completed. In my service i am creating a task. This task will be started or stopped at any time depending on some conditions. My intention is whenever i started my task, i want to display an icon in status bar to know that my task is running like bluetooth icon will be displayed when it is turned ON.

like image 969
Yugandhar Babu Avatar asked Jan 12 '12 13:01

Yugandhar Babu


1 Answers

You need a Notification. Code is talking :)

In your Service:

private NotificationManager mNM;
private int NOTIFICATION = 10002; //Any unique number for this notification

To show the notification:

private void showNotification() {
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.local_service_started);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.status_icon, text, System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);

    // Send the notification.
    mNM.notify(NOTIFICATION, notification);
}

and to hide it, you simply do this:

mNM.cancel(NOTIFICATION); //The same unique notification number.

Here are some clarifications:

  • R.drawable.status_icon : Notification icon
  • R.string.local_service_started : Notification title
  • R.string.local_service_label : Notification latest info (sub-title)
  • MainActivity.class : The Activity that will be launched when the user click the notification
like image 103
iTurki Avatar answered Sep 30 '22 16:09

iTurki