如何更改通知中的按钮?

时间:2015-08-30 10:30:13

标签: android notifications foreground-service

我正在制作前台服务通知,以控制我设备上的功能。现在我通过FlashLight按钮发出通知。此外,我可以使用PendingIntent处理此按钮。而且我想按下另一种颜色的按钮。我怎样才能做到这一点?可能,我错过了一些明显的东西。也许,我可以通过onReceive方法中的上下文来完成它,但我仍然不知道该怎么做。请帮助我。notification

//It's method in Service that I started from MainActivity
    public int onStartCommand(Intent intent, int flags, int startId) {

    Notification notification;
    //Create notification builder
    NotificationCompat.Builder notificationBuilder =
            (NotificationCompat.Builder) new NotificationCompat.Builder(this);
    notification = notificationBuilder.setSmallIcon(R.drawable.white_bulb)
                    .setContentTitle("My Title")
                    .setContentText("My Text")
                    .build();
    //create a remoteViews to this notification
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notificationlayout);
    remoteViews.setImageViewResource(R.id.image, R.drawable.white_bulb);
    remoteViews.setTextViewText(R.id.title, "Popup Notification");
    remoteViews.setTextViewText(R.id.text, "");
    //create a pendingIntent for button in my notification
    Intent switchIntent = new Intent(this, SwitchButtonListener.class);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.switchLight, pendingSwitchIntent);
    notification.contentView = remoteViews;
    //actually run the notification
    startForeground(notificationID, notification);

    return super.onStartCommand(intent, flags, startId);

}  
   //It's method in SwitchButtonListener.class that run when I push the button     
   public void onReceive(Context context, Intent intent) {

    if (!isFlash){
        holdCamera();
        runFlashLight();
        isFlash = true;
    }else {
        stopFlashLight();
        unholdCamera();
        isFlash = false;
    }

}

1 个答案:

答案 0 :(得分:0)

I found solution. My mistake - use Button with setBackground() for image. In this case remoteViews.setImageViewResource(R.id.switchLight, R.drawable.blue_bulb) throw fatal error. Solution - use ImageButton and setImageViewResource() will works right. And actually answer for my question: For changing the button in notification - 1. store an instance of NotificationCompat.Builder that builded my notification, notificationID and RemoteViews (my notification content). 2.Change button src with remoteViews.setImageViewResource() 3.Via notificationManager.notify(notificationID, notificationBuider.build()); So, actually, there is no way to change button in notification. We should recreate whole notification with small different. First paragraph I did with static variables in PopupService. As you can see buttons have another view.it's work fine