有没有办法让 Android 通知在屏幕上停留超过 4 秒。
例如:
电话应用程序有来电通知,当此通知显示(来电)时,它不会离开屏幕,直到用户与通知交互(接受调用/拒绝调用/转到电话应用程序)。然而,我还没有找到一种方法可以使通知在屏幕(前景)上持续超过 4 秒。即使当我设置 FLAG_INSISTENT 和 FLAG_NO_CLEAR 时,通知最后在屏幕上可见 4 - 5 秒...
FLAG_INSISTENT - 在高优先级通知上保持蜂鸣声和振动,但通知仍然会在 4 秒后从屏幕上消失,用户需要向下拖动栏才能“看到”通知。
我正在寻找一种以与手机应用程序相同的方式放置通知的方法,这意味着将通知保留在屏幕上,直到用户与之交互。
以下是主要 Activity 的示例:
我的MainActivity.java:
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private NotificationManagerCompat notificationManager;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = NotificationManagerCompat.from(this);
Intent YesReceive = new Intent(this, com.eddieharari.notifi.Data.class);
YesReceive.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntentYes = PendingIntent.getActivity(this,12345, YesReceive,
0);
Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("My Notify TITLE")
.setContentText("This is my notification Message")
.setPriority(NotificationManagerCompat.IMPORTANCE_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setOngoing(false)
.setAutoCancel(true)
.setContentIntent(pendingIntentYes)
.setPriority(Notification.PRIORITY_MAX)
.build();
notification.flags = notification.flags | Notification.FLAG_INSISTENT | Notification.FLAG_NO_CLEAR;
notificationManager.notify(1, notification);
}
}
我的App.java(我设置通知 channel 的地方)
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("This is channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}
最佳答案
我发现了以下内容:
通知内的全屏 Intent 具有高优先级 = true( Intent 的第二个参数)将通知保留在屏幕顶部,直到用户交互!
使用 FullScreen Intent 时,不要忘记在 list 中请求 fullScreenIntent 权限......
关于Android 通知持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66775593/