태그 보관물: notifications

notifications

Android에서 알림에 버튼을 추가하는 방법은 무엇입니까? 사용자가 화면 상단 (또는 일반적으로 태블릿의 경우

내 앱은 음악을 재생하고 사용자가 화면 상단 (또는 일반적으로 태블릿의 경우 화면 오른쪽 하단)에서 스 와이프하여 알림 화면을 열 때 현재 재생중인 음악을 중지하고 다시 시작하는 버튼을 제시하고 싶습니다. 그들은 원한다.

사용자의 홈 화면에 위젯을 넣을 계획이 아니라 알림에만 적용 할 계획입니다. 어떻게 할 수 있습니까?



답변

작업에 대한 인 텐트 (이 경우 재생 중지)를 만들고 알림에 작업 버튼으로 추가 할 수 있습니다.

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

Android 문서를 참조하십시오 .


답변

알림에 작업 버튼 추가

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

자세한 내용은 https://developer.android.com/training/notify-user/build-notification.html을 방문
하십시오.


답변

내가 사용한 솔루션을 제공하려고 노력할 것이며 대부분의 음악 플레이어도 동일한 기술을 사용하여 알림 표시 줄에 플레이어 컨트롤을 표시합니다.

Media Player 및 모든 컨트롤을 관리하는 데 사용되는 서비스를 실행하고 있습니다. 활동 사용자 제어는 예를 들어 서비스에 인 텐트를 전송하여 서비스와 상호 작용합니다.

 Intent i = new Intent(MainActivity.this, MyRadioService.class);
        i.setAction(Constants.Player.ACTION_PAUSE);

        startService(i);

인 텐트를 수신하고 Service 클래스에서 작업을 수행하려면 Service의 onStartCommand 메서드에서 다음 코드를 사용하고 있습니다.

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {


    if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) {
        if(mediaPlayer.isPlaying()) {
            pauseAudio();
        }
    }

이제 귀하의 질문에 대한 정확한 답변으로 컨트롤을 재생하여 알림을 표시합니다. 다음 메서드를 호출하여 컨트롤과 함께 알림을 표시 할 수 있습니다.

   //    showNotification
private void startAppInForeground() {
//  Start Service in Foreground

    // Using RemoteViews to bind custom layouts into Notification
    RemoteViews views = new RemoteViews(getPackageName(),
            R.layout.notification_status_bar);

// Define play control intent 
   Intent playIntent = new Intent(this, MyRadioService.class);
    playIntent.setAction(Constants.Player.ACTION_PLAY);

// Use the above play intent to set into PendingIntent
    PendingIntent pplayIntent = PendingIntent.getService(this, 0,
            playIntent, 0);

// binding play button from layout to pending play intent defined above 
views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
views.setImageViewResource(R.id.status_bar_play,
            R.drawable.status_bg);

Notification status = null;
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        status = new Notification.Builder(this).build();
    }

  status.flags = Notification.FLAG_ONGOING_EVENT;
    status.icon = R.mipmap.ic_launcher;
    status.contentIntent = pendingIntent;
    startForeground(Constants.FOREGROUND_SERVICE, status);

} 이것이 정말 도움이되기를 바랍니다. 그리고 원하는 것을 얻을 수 있습니다. 즐거운 코딩 되세요 🙂


답변

    // It shows buttons on lock screen (notification).

Notification notification = new Notification.Builder(context)
    .setVisibility(Notification.VISIBILITY_PUBLIC)
    .setSmallIcon(R.drawable.NotIcon)
    .addAction(R.drawable.ic_prev, "button1",ButtonOneScreen)
    .addAction(R.drawable.ic_pause, "button2", ButtonTwoScreen)
   .....
    .setStyle(new Notification.MediaStyle()
    .setShowActionsInCompactView(1)
    .setMediaSession(mMediaSession.getSessionToken())
    .setContentTitle("your choice")
    .setContentText("Again your choice")
    .setLargeIcon(buttonIcon)
    .build();

자세한 내용은 여기를 참조 하십시오 여기를 클릭하십시오


답변

Ankit Gupta대답 외에도 MediaSession (API> 21)을 사용하여 네이티브 mediaController 뷰 를 추가 할 수 있다고 생각합니다 .

notificationBuilder
        .setStyle(new Notification.MediaStyle()
            .setShowActionsInCompactView(new int[]{playPauseButtonPosition})  // show only play/pause in compact view
            .setMediaSession(mSessionToken))
        .setColor(mNotificationColor)
        .setSmallIcon(R.drawable.ic_notification)
        .setVisibility(Notification.VISIBILITY_PUBLIC)
        .setUsesChronometer(true)
        .setContentIntent(createContentIntent(description)) // Create an intent that would open the UI when user clicks the notification
        .setContentTitle(description.getTitle())
        .setContentText(description.getSubtitle())
        .setLargeIcon(art);

출처 : 튜토리얼

사용자 정의보기를 만들고 알림 영역에 표시 할 수도 있습니다 . 여기 에서 첫 번째 답변 이 좋습니다.


답변

Android Pie로 테스트 된 코드입니다. 이들은 모두 동일한 서비스 클래스에 포함됩니다.

알림 표시 :

public void setNotification() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
    NotificationChannel channel = new NotificationChannel("a", "status", NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("notifications");
    notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);

    }
else
    notificationManager =  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


Receiver.service = this;
Notification.MediaStyle style = new Notification.MediaStyle();

notification = new Notification.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Notification")
        .addAction(R.drawable.close_icon,  "quit_action", makePendingIntent("quit_action"))
        .setStyle(style);

style.setShowActionsInCompactView(0);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
    notification.setChannelId("a");
    }

// notificationManager.notify(123 , notification.build()); // pre-oreo
startForeground(126, notification.getNotification());
}

도우미 기능 :

public PendingIntent makePendingIntent(String name)
    {
    Intent intent = new Intent(this, FloatingViewService.Receiver.class);
    intent.setAction(name);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    return pendingIntent;
    }

조치를 처리하려면 :

static public class Receiver extends BroadcastReceiver {
static FloatingViewService service;

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

    String whichAction = intent.getAction();

    switch (whichAction)
        {

        case "quit_action":
            service.stopForeground(true);
            service.stopSelf();
            return;

        }

    }
}

매니페스트도 업데이트해야합니다.

<receiver android:name=".FloatingViewService$Receiver">
        <intent-filter>
            <action android:name="quit_action" />
        </intent-filter>
    </receiver>


답변

아래와 같이 버튼을 추가 할 수 있으며 해당 버튼에 대한 작업을 수행 할 수 있습니다.

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_logo)
                        .setAutoCancel(true)
                        .setContentTitle(name)
                        .setContentText(body)
                        .setGroupSummary(true)
                        .addAction(android.R.drawable.ic_menu_directions, "Mark as read", morePendingIntent);

// morePendingIntent (작업 수행)

  PendingIntent morePendingIntent = PendingIntent.getBroadcast(
                        this,
                        REQUEST_CODE_MORE,
                        new Intent(this, NotificationReceiver.class)
                                .putExtra(KEY_INTENT_MORE, REQUEST_CODE_MORE)
                                .putExtra("bundle", object.toString()),
                        PendingIntent.FLAG_UPDATE_CURRENT
                );