2014-12-28 2 views
4

Чтобы лучше поддерживать уведомления Android 5, я теперь уведомляю о том, что уведомление моего приложения видимо «общедоступно». После рассмотрения ответов на Lollipop Notification setVisibility() Does Not Work? уведомление теперь отображается как ожидалось. Однако, когда я хочу нажать кнопку действия уведомления, сначала я должен разблокировать устройство, которое не требуется. (Действие показывает, что база паролей разблокирована и кнопка действия будет блокировать базу данных.)Кнопка действия уведомления не может быть нажата в окне блокировки

Это код, я использую создание уведомлений (с помощью Mono Xamarin для Android):

NotificationCompat.Builder builder = 
       new NotificationCompat.Builder(this) 
        .SetOngoing(true) 
        .SetSmallIcon(Resource.Drawable.ic_notify) 
        .SetLargeIcon(...) 
        .SetVisibility((int)Android.App.NotificationVisibility.Public) 
        .SetContentTitle(...) 
        .SetContentText(...); 

builder.AddAction(Resource.Drawable.ic_action_lock, GetString(Resource.String.menu_lock), PendingIntent.GetBroadcast(this, 0, new Intent(Intents.LockDatabase), PendingIntentFlags.UpdateCurrent)); 

где this - экземпляр службы.

Я знаю, что у уведомлений MediaStyle есть кнопки с кнопками, но это похоже на взломать MediaStyle, хотя это не касается медиа. Есть ли способ заставить мои действия использовать экран блокировки?

+0

вы пытаетесь создать уведомление хедз-ап? – user2511882

ответ

4

Вместо добавления действия определите свой собственный макет уведомлений и подключите pendingIntent, чтобы запустить его через RemoteView. (Приведенный ниже пример основан на хол выглядеть и чувствовать себя и по-прежнему нужно будет обновляться для леденца. Вы можете найти все të правильные ресурсы в папке андроида-21/данные/Реза вашего SDK)

// NOTE: while creating pendingIntent: requestcode must be different! 
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(myService) 
     .setSmallIcon(R.drawable.notification_icon).setContentTitle("My Title") 
     .setContentText("Service running in the background"); 
Intent openIntent = new Intent(MainActivity.this, MainActivity.class); 
PendingIntent pOpenIntent = PendingIntent.getActivity(this, 0, openIntent, 0); 
mBuilder.setContentIntent(pOpenIntent); 

// Notification with exit button if supported 
String ACTION_NOTIFICATION_EXITACTIVITY = "com.jmols.example.exitactivity"; 
Intent exitIntent = new Intent(); 
exitIntent.setAction(ACTION_NOTIFICATION_EXITACTIVITY); 
PendingIntent pExitIntent = PendingIntent.getBroadcast(this, 1, exitIntent, 0); 
RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification_discoveryservice); 
view.setOnClickPendingIntent(R.id.notification_closebtn_ib, pExitIntent); 
mBuilder.setContent(view); 

При компоновке уведомлений:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:internal="http://schemas.android.com/apk/prv/res/android" 
    android:id="@+id/status_bar_latest_event_content" 
    android:layout_width="match_parent" 
    android:layout_height="64dp" 
    internal:layout_maxHeight="64dp" 
    internal:layout_minHeight="64dp" > 

    <ImageView 
     android:id="@+id/notification_icon_iv" 
     android:layout_width="64dp" 
     android:layout_height="64dp" 
     android:padding="10dp" 
     android:layout_alignParentLeft="true" 
     android:scaleType="center" 
     android:src="@drawable/notification_icon" 
     android:background="#3333B5E5" /> 

    <ImageButton 
     android:id="@+id/notification_closebtn_ib" 
     android:layout_width="40dp" 
     android:layout_height="40dp" 
     android:layout_alignParentRight="true" 
     android:layout_centerVertical="true" 
     android:scaleType="centerInside" 
     android:src="@drawable/notification_exitbtn" 
     android:background="@drawable/notification_imagebtn_bg"/> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="fill_vertical" 
     android:gravity="top" 
     android:minHeight="64dp" 
     android:layout_toRightOf="@id/notification_icon_iv" 
     android:layout_toLeftOf="@id/notification_closebtn_ib" 
     android:orientation="vertical" 
     android:paddingBottom="2dp" 
     android:paddingEnd="8dp" 
     android:paddingTop="2dp" > 

     <TextView 
      android:id="@+id/notification_title_tv" 
      style="@android:style/TextAppearance.StatusBar.EventContent.Title" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="8dp" 
      android:ellipsize="marquee" 
      android:paddingTop="6dp" 
      android:singleLine="true" 
      android:text="JMols Service" /> 

     <TextView 
      android:id="@+id/notification_contenttext_tv" 
      style="@android:style/TextAppearance.StatusBar.EventContent" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="8dp" 
      android:ellipsize="marquee" 
      android:singleLine="true" 
      android:text="Service running in the background" /> 

    </LinearLayout> 

</RelativeLayout> 

И на фоне уведомления является:

<selector xmlns:android="http://schemas.android.com/apk/res/android" 
    android:exitFadeDuration="@android:integer/config_mediumAnimTime"> 

    <item android:state_pressed="true" android:drawable="@drawable/notification_bg_normal_pressed" /> 
    <item android:state_pressed="false" android:drawable="@drawable/notification_bg_normal" /> 
</selector> 

notification_bg_normal.9 notification_bg_normal_pressed.9

И уведомление ImageButton фон:

<selector xmlns:android="http://schemas.android.com/apk/res/android" 
    android:exitFadeDuration="@android:integer/config_mediumAnimTime"> 

    <item android:state_pressed="true" android:drawable="@drawable/notification_imagebtn_bg_normal_pressed" /> 
    <item android:state_pressed="false" android:drawable="@drawable/notification_imagebtn_bg_normal" /> 
</selector> 

notification_imagebtn_bg_normal.9.png notification_imagebtn_bg_normal_pressed.9.png

+1

Я действительно надеялся, что есть более простое решение, но похоже, что ваш путь - это один. Благодаря! – Philipp

+0

Является ли тот факт, что это услуга является значительной частью этого разрешения? Я не мог заставить его работать, но это может быть нечто совершенно другое. (для заинтересованных, см. http://stackoverflow.com/questions/33724567/lock-screen-notifications-with-clickable-content) – Nanne

0

Я думаю, что Android только позволяет управлять воспроизведением мультимедиа с экрана блокировки, другие уведомления должны разблокировать экран, чтобы начать работу для обеспечения безопасности. Например, вы можете захотеть узнать, что вы получаете новые письма, возможно, вам захочется показать, что некоторые сообщения только что приходят, но вам может не понадобиться лазейка для доступа к вашей учетной записи электронной почты, когда устройство заблокировано. В средствах управления воспроизведением мультимедиа случаи использования не имеют таких проблем безопасности.