如果我的Android Xamarin应用在后台运行,如何获取通知消息并将其显示在前台?

3

我很抱歉,我不是一位经验丰富的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();
    }
 }
1个回答

3

我似乎找不到或想不出如何让通知消息的点击将我的运行中应用程序推至前台(仅当它不在前台时)

您需要告诉通知在单击时要执行什么操作(启动哪个activity)。

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的内容,了解上述代码中每个项目的含义以及其他选项。


这正是我所想的,我正在研究我不熟悉的挂起意图。但看起来你给出的是一个实际的答案,所以让我快速尝试一下。谢谢。 - user192632
完美运行,而且你甚至明智地使用了PendingIntentFlags.OneShot,这正是我所需要的。谢谢。我会标记为答案。 - user192632

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接