隐藏前台通知



我正在尝试创建一个沉默的Android前台通知,并允许用户手动隐藏前台通知。我已经创建了一个自定义BroadcastReceiver来打开通知设置页面,并使用这里的代码设置通知的意图。

但是,这会导致崩溃,并出现以下错误:

' start前台通知错误'

MyService.cs:

class MyService : Service
{
private Handler handler;
private Action runnable;
private bool isStarted;
private int DELAY_BETWEEN_LOG_MESSAGES = 5000;
private int NOTIFICATION_SERVICE_ID = 1001;
private int NOTIFICATION_AlARM_ID = 1002;
private string NOTIFICATION_CHANNEL_ID = "1003";
private string NOTIFICATION_CHANNEL_NAME = "MyChannel";
public override void OnCreate()
{
base.OnCreate();
handler = new Handler();
// push a notification every 5 seconds
runnable = new Action(() =>
{
if (isStarted)
{
DispatchNotificationThatAlarmIsGenerated();
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
}
});
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if (isStarted)
{
// service is already started
}
else
{
CreateNotificationChannel();
DispatchNotificationThatServiceIsRunning();
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
isStarted = true;
}
return StartCommandResult.Sticky;
}
public override void OnTaskRemoved(Intent rootIntent)
{
//base.OnTaskRemoved(rootIntent);
}
public override IBinder OnBind(Intent intent)
{
// return null because this is a pure started service. A hybrid service would return a binder that would
// allow access to the GetFormattedStamp() method.
return null;
}
public override void OnDestroy()
{
// stop the handler
handler.RemoveCallbacks(runnable);
// remove the notification from the status bar
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Cancel(NOTIFICATION_SERVICE_ID);
isStarted = false;
base.OnDestroy();
}
private void CreateNotificationChannel()
{
// notification Channel
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationImportance.Low);
notificationChannel.LockscreenVisibility = NotificationVisibility.Secret;
notificationChannel.SetSound(null, null);
notificationChannel.EnableLights(false);
notificationChannel.EnableVibration(false);
NotificationManager notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);
notificationManager.CreateNotificationChannel(notificationChannel);
}
// start a foreground notification to keep alive 
private void DispatchNotificationThatServiceIsRunning()
{
Intent intent = new Intent(this, typeof(CustomReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(
this,
1,
intent,
PendingIntentFlags.UpdateCurrent
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
.SetAutoCancel(false)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentIntent(pendingIntent)
.SetContentTitle("Hide Notification")
.SetContentText("To hide the notification, click and uncheck 'Hidden Notification Service'");
StartForeground(NOTIFICATION_SERVICE_ID, builder.Build());
}
// every 5 seconds push a notificaition
private void DispatchNotificationThatAlarmIsGenerated()
{
Intent intent = new Intent(this, typeof(CustomReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(
this,
1,
intent,
PendingIntentFlags.UpdateCurrent
);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "default")
.SetAutoCancel(false)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentIntent(pendingIntent)
.SetVisibility(NotificationCompat.VisibilitySecret)
.SetContentTitle("Hide Notification")
.SetContentText("To hide me, click and uncheck 'Hidden Notification Service'");
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_AlARM_ID, notificationBuilder.Build());
}
}

BroadcastReceiver.cs:

[BroadcastReceiver(Enabled = true)]
public class CustomReceiver : BroadcastReceiver
{
private string NOTIFICATION_CHANNEL_ID = "1003";
public override void OnReceive(Context context, Intent intent)
{
Intent i = new Intent(Android.Provider.Settings.ActionChannelNotificationSettings)
.PutExtra(Android.Provider.Settings.ExtraAppPackage, context.PackageName)
.PutExtra(Android.Provider.Settings.ExtraChannelId, NOTIFICATION_CHANNEL_ID)
.SetFlags(ActivityFlags.NewTask);
context.StartActivity(i);
}
}

如何创建前台静音通知,并在通知被点击时打开通知设置页面?

然而,这会导致崩溃,并出现以下错误:' start前台通知错误'

你需要在Mainactivity中创建通知通道,然后调用CreateNotificationChannel() Mainactivity . oncreate()方法。

void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification 
// channel on older versions of Android.
return;
}
var name = "Local Notifications";
var description = "The count from MainActivity";
var channel = new NotificationChannel("location_notification", name, NotificationImportance.Default)
{
Description = description
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}

然后在MyService

中设置Notification的channelId
Intent intent = new Intent(this, typeof(CustomReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(
this,
1,
intent,
PendingIntentFlags.UpdateCurrent
);
var notification = new Notification.Builder(this,default)
.SetChannelId("location_notification")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(Resources.GetString(Resource.String.notification_text))
.SetSmallIcon(Resource.Drawable.ic_stat_name)
.SetContentIntent(pendingIntent)
.SetOngoing(true)
.AddAction(BuildRestartTimerAction())
.AddAction(BuildStopServiceAction())
.Build();

// Enlist this instance of the service as a foreground service
StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification);

如何创建前台静音通知,并在单击通知时打开通知设置页面?

创建一个自定义BroadcastReceiver来打开通知设置页面,并为通知设置意图以添加click事件。

[BroadcastReceiver(Enabled = true)]
public class CustomReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Intent i = new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings, Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName))//Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS          
.SetFlags(ActivityFlags.NewTask);
context.StartActivity(i);
}
}

最新更新