Android - implementing startForeground for a service?

前端 未结 11 1272
不思量自难忘°
不思量自难忘° 2020-11-22 06:26

So I\'m not sure where/how to implement this method to make my service run in the foreground. Currently I start my service by the following in another activity:

<         


        
11条回答
  •  日久生厌
    2020-11-22 07:28

    @mikebertiean solution almost did the trick, but I had this problem with additional twist -- I use Gingerbread system and I didn't want to add some extra package just to run notification. Finally I found: https://android.googlesource.com/platform/frameworks/support.git+/f9fd97499795cd47473f0344e00db9c9837eea36/v4/gingerbread/android/support/v4/app/NotificationCompatGingerbread.java

    then I hit additional problem -- notification simply kills my app when it runs (how to solve this problem: Android: How to avoid that clicking on a Notification calls onCreate()), so in total my code in service looks like this (C#/Xamarin):

    Intent notificationIntent = new Intent(this, typeof(MainActivity));
    // make the changes to manifest as well
    notificationIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
    PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
    Notification notification = new Notification(Resource.Drawable.Icon, "Starting service");
    notification.SetLatestEventInfo(this, "MyApp", "Monitoring...", pendingIntent);
    StartForeground(1337, notification);
    

提交回复
热议问题