在IntentService中显示通知

时间:2015-03-20 12:57:58

标签: android

我需要在意图服务的方法中显示通知,我将上下文修改为“getApplicationContext”,但它没有显示任何内容。

我正在使用android示例:http://developer.android.com/guide/topics/ui/notifiers/notifications.html

 private void notf_SinConexion()
    {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder( getApplicationContext() )
                        .setSmallIcon( R.drawable.ic_action_action_alarm_on )
                        .setContentTitle( "Title" )
                        .setContentText( "Message" );

        Intent resultIntent = new Intent( getApplicationContext(), MainActivity.class );
        TaskStackBuilder stackBuilder = TaskStackBuilder.create( getApplicationContext() );
        stackBuilder.addParentStack( MainActivity.class );

        stackBuilder.addNextIntent( resultIntent );
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent( resultPendingIntent );
        NotificationManager mNotificationManager =
                (NotificationManager) getApplicationContext().getSystemService( Context.NOTIFICATION_SERVICE );
        // mId allows you to update the notification later on.
        mNotificationManager.notify( 10, mBuilder.build() );
    }

1 个答案:

答案 0 :(得分:2)

首先,您需要阅读有关如何使用Notifications的文章。

接下来使用它来发送通知,您可以在服务类中从客户端接收一些数据时编写此代码。

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