簡體   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