2015-08-07 3 views
4

Я реализую пользовательское push-уведомление, интегрируя RemoteViews. Проблема в том, что кнопки в удаленном режиме не отображаются. Я не понимаю, что я сделал.RemoteView не отображает кнопки в пользовательском уведомлении

Код:

public class AlarmReceiver extends BroadcastReceiver { 
    Bitmap bannerimage; 
    private static int MY_NOTIFICATION_ID=1; 
    NotificationManager notificationManager; 
    Notification myNotification; 

    @SuppressLint("NewApi") 
    @Override 
    public void onReceive(Context context, Intent intent) { 


     bannerimage = BitmapFactory.decodeResource(context.getResources(), 
       R.drawable.dummyturkey); 
     MY_NOTIFICATION_ID=1; 
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), 
       R.layout.custom_push_layout); 
     Intent myIntent = new Intent(context,DoSomething.class); 
     PendingIntent pendingIntent = PendingIntent.getActivity(
       context, 
       MY_NOTIFICATION_ID, 
       myIntent, 
       Intent.FLAG_ACTIVITY_NEW_TASK); 
     Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

     String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()); 
     System.out.println("Alarm fired AlarmReciever:"+mydate); 

     remoteViews.setImageViewBitmap(R.id.imgbanner,bannerimage); 

     Notification myNotification = new Notification.Builder(context) 
     .setContent(remoteViews) 
     .setSmallIcon(R.drawable.ic_launcher) 
     .setContentIntent(pendingIntent) 
     .setWhen(System.currentTimeMillis()) 
     .setSound(alarmSound) 
     .setAutoCancel(false).build(); 



     NotificationManager notificationManager = 
       (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(MY_NOTIFICATION_ID, myNotification); 


     } 

    } 

XML-файла custom_push_layout.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#ffffff" 
    android:orientation="vertical" > 

    <ImageView 
     android:id="@+id/imgbanner" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:adjustViewBounds="true" 
     android:background="@drawable/ic_launcher" 
     android:scaleType="fitXY" /> 

    <TextView 
     android:id="@+id/txt1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="This chicken has send you a friend request" /> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

     <Button 
      android:id="@+id/btnaccept" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Accept" /> 

     <Button 

      android:id="@+id/btncancel" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_toRightOf="@+id/btnaccept" 

      android:text="Cancel" /> 
    </RelativeLayout> 

</LinearLayout> 

Уведомление приходит, но это только отображение ImageView, а не кнопок или TextView в пределах раскладка.

Пожалуйста, дайте решение со ссылкой на приведенный выше код, т. Е. что я делаю неправильно или что у меня отсутствует. Пожалуйста, не публикуйте свежий код.

ответ

2

С помощью Notification.Builder(context).setContent вы устанавливаете стандартную макет вида для уведомления. Согласно Notifications API Guide, нормальная высота макета вида ограничена 64dp.

Высота, доступная для пользовательского макета уведомления, зависит от вида уведомления. Обычные макеты просмотра ограничены 64 дп, а расширенные макеты представлений ограничены 256 дп.

Что нужно сделать, это установить contentView и bigContentView в объект уведомления. Создайте два отдельных макета, один для обычного и один для макета большого представления, и создайте два RemoteViews.

RemoteViews customViewSmall = new RemoteViews(context.getPackageName(), R.layout.custom_notification_small); 
RemoteViews customViewBig = new RemoteViews(context.getPackageName(), R.layout.custom_notification_big); 

... 
set the values of the views 
... 

Notification myNotification = new Notification.Builder(context) 
     .setSmallIcon(R.drawable.ic_launcher) 
     .setContentIntent(pendingIntent) 
     .setWhen(System.currentTimeMillis()) 
     .setSound(alarmSound) 
     .setAutoCancel(false).build(); 

myNotification.contentView = customViewSmall; 
myNotification.bigContentView = customViewBig; 

Пожалуйста, обратите внимание, что bigContentView доступен из API16. Также в UI xml добавьте цвет для всех TextView просмотров.

EDIT: В опорном v4 библиотеке 24, NotificationBuilderCompat имеет новый метод setCustomBigContentView(), поэтому вместо того, чтобы установка remoteViews к Notification объекта, просто используйте NotificationBuilderCompat. Вы можете увидеть здесь: Notification API Guide.

Результат:

Result:

Смежные вопросы