你可以通过以下代码示例来解决在滑动时移除通知的问题:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "notification_channel";
private static final int NOTIFICATION_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
// 创建自定义布局的通知
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
// 设置通知中的内容和样式
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContent(remoteViews)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(false);
Notification notification = builder.build();
// 显示通知
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification Channel";
String description = "Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
上述代码中:
首先,我们使用createNotificationChannel()
方法来创建通知渠道,这是Android 8.0(API level 26)及以上版本所必需的。
然后,我们创建一个自定义布局的通知RemoteViews
,你可以在R.layout.custom_notification_layout
中定义自己的布局。
接下来,我们使用NotificationCompat.Builder
来设置通知的内容和样式。我们指定了通知图标、自定义布局以及通知的优先级和自动取消行为。
最后,我们使用NotificationManager
来显示通知,并指定了通知的ID为NOTIFICATION_ID
。
通过以上代码,你可以在滑动时阻止通知被移除,只有当用户点击通知或者你手动取消通知时,通知才会被移除。
上一篇:奥利奥系统上的蓝牙数据丢失