How to show android notification and app icon

I have a service and I want to send a notification. Too bad, a notification object requires a context, such as Activity, not a service.

Do you know any way to get past? I tried to create an Activity for each notification, this seems ugly, and I cannot find a way to start the Activity without any representation.

I also want to send the application icon in a notification to show the top of the screen icon

+4
source share
1 answer

Here is the working code that creates a notification for the service itself. hope this helps you

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
   @Override
   public IBinder onBind(Intent arg0) {
      return null;
   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {




     //We get a reference to the NotificationManager
       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

       String MyText = "Reminder";
       Notification mNotification = new Notification(R.drawable.ic_launcher, MyText, System.currentTimeMillis() );
       //The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears

       String MyNotificationTitle = "Medicine!";
       String MyNotificationText  = "Don't forget to take your medicine!";

       Intent MyIntent = new Intent(Intent.ACTION_VIEW);
       PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
       //A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent

       mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);

       int NOTIFICATION_ID = 1;
       notificationManager.notify(NOTIFICATION_ID , mNotification);  
       //We are passing the notification to the NotificationManager with a unique id.

      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}
0
source

All Articles