如何显示android通知和应用程序图标

时间:2014-11-06 18:45:50

标签: android

我正在运行服务,并希望发送通知。太糟糕了,通知对象需要一个上下文,比如一个Activity,而不是一个服务。

你知道通过什么方式吗?我尝试为每个通知创建一个活动,看起来很难看,我找不到一种方法来启动没有任何视图的活动。

我还想将我的应用程序图标发送到通知,以显示图标顶部的

1 个答案:

答案 0 :(得分:0)

这是一个工作代码,它从服务本身创建通知。 希望它会对你有所帮助,

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();
   }
}