Alexander Man
Alexander Man

Reputation: 63

Show current Activity by clicking Foreground Service Notification

How to show Foreground Service activity by clicking Notification? When I use my code, it starts new activity, but I need the activity, where service is working. Here is my code (Android Oreo):

 public class APSService : Service
    {
        public static bool isRunning = false;

        public override void OnCreate()
        {
            base.OnCreate();
        }

        public override void OnDestroy()
        {
            isRunning = false;
            base.OnDestroy();
        }



        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            isRunning = true;
            byte[] input = intent.GetByteArrayExtra("inputExtra");

            Intent notificationIntent = new Intent(this, Java.Lang.Class.FromType((typeof(MainActivity))));

            PendingIntent pendingIntent = PendingIntent.GetActivity(this,
                0, notificationIntent, 0);

            var builder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                .SetContentTitle("APS Service")
                .SetSmallIcon(Resource.Drawable.notifypump)
                .SetContentText("Start program...")
                .SetContentIntent(pendingIntent);

            Notification notification = builder.Build();

            StartForeground(1, notification);

            //do heavy work on background thread

            return StartCommandResult.NotSticky;
        }


        public override IBinder OnBind(Intent intent)
        {
            return null;
        }
    }

And in MainActivity in OnCreate:

 protected override void OnCreate(Bundle savedInstanceState)
        {
            if (!APSService.isRunning)
            {
                createNotificationChannel();
                startService();
            }
            else
            {
                NotificationChannel serviceChannel = new NotificationChannel
                       (
                           CHANNEL_ID,
                           "APS service Channel",
                           NotificationImportance.Default
                       );
                notificationManager = (NotificationManager)GetSystemService(Java.Lang.Class.FromType((typeof(NotificationManager))));
                notificationManager.CreateNotificationChannel(serviceChannel);
                UpdateNotification("Loading...");
                APSService.isRunning = true;

            }
}

I hope you would help for solving this problem. Thanks a lot.

Upvotes: 2

Views: 1662

Answers (2)

Leon Lu
Leon Lu

Reputation: 9274

I write a demo about it, here is a GIF.

enter image description here

You can achieve the festure like following code.

 [Service]
class MyForegroundService : Service
{
    public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        CreateNotificationChannel();
        string messageBody = "service starting";
       // / Create an Intent for the activity you want to start
       Intent resultIntent = new Intent(this,typeof(Activity1));
       // Create the TaskStackBuilder and add the intent, which inflates the back stack
       TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
       stackBuilder.AddNextIntentWithParentStack(resultIntent);
       // Get the PendingIntent containing the entire back stack
       PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
       var notification = new Notification.Builder(this, "10111")
        .SetContentIntent(resultPendingIntent)
        .SetContentTitle("Foreground")
        .SetContentText(messageBody)
        .SetSmallIcon(Resource.Drawable.main)
        .SetOngoing(true)
        .Build();
        StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
         //do you work
        return StartCommandResult.Sticky;


    }
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    void CreateNotificationChannel()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            // Notification channels are new in API 26 (and not a part of the
            // support library). There is no need to create a notification
            // channel on older versions of Android.
            return;
        }

        var channelName = Resources.GetString(Resource.String.channel_name);
        var channelDescription = GetString(Resource.String.channel_description);
        var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
        {
            Description = channelDescription
        };

        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }

}

Here is my demo. https://github.com/851265601/ForegroundServiceDemo

Upvotes: 1

Leo Jebran
Leo Jebran

Reputation: 174

It's not clear to me what Activity you want to open

How to show Foreground Service activity

A Foreground service runs independently from your app

You are launching the MainActivity here:

Intent notificationIntent = new Intent(this,Java.Lang.Class.FromType((typeof(MainActivity))));

can you clarify what do want to do here?

ps: I know it's not an answer, can't comment yet

Upvotes: 0

Related Questions