繁体   English   中英

如果在后台Android Xamarin中,获取通知消息以在前台显示我的应用程序

[英]Getting a notification message to show my app in foreground if in background Android Xamarin

我提前道歉,因为我不是一个特别有经验的Android开发人员,我正在使用C#在Xamarin上开展一个Android项目。 我希望这个问题不是重复的,因为我似乎找不到一个,但如果是,请将其标记为这样,我很乐意删除这个问题。

我希望我的droid应用程序的图标在启动时及其运行时显示在通知栏中。 当应用程序进入销毁事件时,我希望删除图标和消息。 到目前为止,我似乎已经失败了,但我似乎无法找到或弄清楚如何点击通知消息将我正在运行的应用程序带到前台(仅当它还没有)。 我想我的代码对此采取了错误的总体方向,也许这涉及即将到来的意图或类似的东西? 这是我的代码。 也许我很接近或者说我的方向错了,但是任何人都可以给予的任何帮助或指示都会非常感激。

[Activity(Label = "MyActivity", MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
    Notification notification = null;
    NotificationManager notificationManager = null;
    const int notificationId = 0;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        Notification.Builder builder = new Notification.Builder(this)
                                           .SetContentTitle("My App is Running")
                                           .SetContentText("Show in forground")
                                           .SetSmallIcon(Resource.Drawable.Icon);

        // Build the notification:
        notification = builder.Build();

        // Get the notification manager:
        notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

        // Publish the notification:
        notificationManager.Notify(notificationId, notification);
    }

    protected override void OnDestroy()
    {
        Log.Debug(logTag, "Location app is becoming inactive");
        notificationManager.Cancel(notificationId);
        base.OnDestroy();
    }
 }

我似乎无法找到或弄清楚如何点击通知消息将我正在运行的应用程序带到前台(仅当它尚未出现时)

您需要在通知中说明单击时需要执行的操作(要启动的活动)。

var intent = new Intent(context, typeof(MainActivity)); 
//activity will not be launched if it is already running at the top of the history stack.
intent.AddFlags(ActivityFlags.SingleTop);   

//Flag indicating that this PendingIntent can be used only once.
var pendingIntent = PendingIntent.GetActivity(context, 0
                                             , intent, PendingIntentFlags.OneShot);
Notification.Builder builder = new Notification.Builder(this)
                                           .SetContentTitle("My App is Running")
                                           .SetContentText("Show in forground")
                                           .SetSmallIcon(Resource.Drawable.Icon)
                                           .SetContentIntent(pendingIntent);

阅读有关Notification.Builder的更多信息,了解上述代码的每个项目的含义以及您拥有的其他选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM