2016-08-04 107 views
2

我提前道歉,因为我不是一个特别有经验的Android开发人员,我正在使用C#编写Xamarin中的Android项目。我希望这个问题不是重复的,因为我似乎还找不到一个问题,但如果是这样,请将其标记为此,我会很乐意删除该问题。在前台显示我的应用程序在后台显示我的应用程序Android Xamarin

我希望我的机器人应用程序的图标在它启动并运行时显示在通知栏中。我想要在应用程序进入销毁事件时移除图标和消息。到目前为止,我似乎有这种情况,但我似乎无法找到或弄清楚如何点击通知消息将我的正在运行的应用程序放到前台(仅在尚未运行时)。我认为我正在为我的代码采取错误的大方向,也许这涉及即将到来的意图或类似的东西?这是我的代码。也许我很接近,或者我的方向不对,但任何人都可以提供的帮助或指点将不胜感激。

[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(); 
    } 
} 

回答

2

我似乎无法找到或弄清楚如何使 通知消息的点击把我跑的应用程序到前台运行(只有当它 尚未)

你需要告诉通知当它被点击时它需要做什么(开始哪个活动)。

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知道上面的代码的每一个项目意味着,你有什么其他选择。

+0

这就是我的想法,我正在研究我不熟悉的未决意图。但它看起来像你给的是一个实际的答案,所以让我试试它很快。谢谢。 – user192632

+0

完美的作品,明智地使用了PendingIntentFlags.OneShot,而这恰好是我所需要的。谢谢。我会标记为答案。 – user192632

相关问题