服务完成后,在状态栏上发送通知

时间:2013-11-30 19:01:17

标签: android

我有一个使用服务下载图片的应用程序,但我希望在下载完成时通知用户,即使用户在应用程序之外(状态栏中的通知)也适用于minSdkVersion =“ 8“,我知道有一些关于此的答案,但我没有得到通知的工作:这里有一些我的代码(它的工作原理只是通知是问题):

public class saveJsonContact1Service extends IntentService {

    private static FileOutputStream fos;

    private int result = Activity.RESULT_CANCELED;

    public saveJsonContact1Service() {
        super("saveJsonContact1Service");
      }

    @Override
      protected void onHandleIntent(Intent intent) {

        downloadImages();//To download images


        sendNotification();//To send a notification after the donwloadImages() method has ended

      }


      private void sendNotification(){

          CharSequence sns = "content";
          CharSequence sns2 = "content";

          NotificationManager notificationManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new Notification(/* your notification */);
                PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
                notification.setLatestEventInfo(this, sns, sns2, pendingIntent);
                notificationManager.notify(0, notification);
      }
      }

如何修改sendNotification()? 感谢

1 个答案:

答案 0 :(得分:3)

试试这个:

private void sendNotification(){

    CharSequence title = "The title";
    CharSequence message = "My message";

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                      .setSmallIcon(R.drawable.ic_launcher)
                      .setAutoCancel(true)
                      .setContentTitle(title);

    mBuilder.setContentText(message);
    mBuilder.setTicker(message);
    mBuilder.setWhen(System.currentTimeMillis());

    NotificationManager notificationManager =   
           (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
    mBuilder.setContentIntent(pendingIntent);
    notificationManager.notify(0, mBuilder.build());
}