简体   繁体   中英

StopForeground doesn't stop foreground service

In my app, i let the user download files. Since its a long action that the user is aware of, i decided to use a service, and start it as a foreground service.I want the service to fire off, finish the download and terminate itself,it shouldn't run all the time.

Here is the call i'm making to start the service, from my main activity.

Intent intent = new Intent(this, typeof(DownloaderService));
intent.PutExtra("id", ID);
StartService(intent);  

Here is how i start the service as an foreground service, this is inside DownloaderService class

public override void OnCreate()
{
    //Start this service as foreground
    Intent notificationIntent = new Intent(this, typeof(VideoDownloaderService));

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

    Notification notification = new Notification.Builder(this)
                       .SetSmallIcon(Resource.Drawable.Icon)
                       .SetContentTitle("Initializing")
                       .SetContentText("Starting The Download...")
                       .SetContentIntent(pendingIntent).Build();

    StartForeground(notificationID, notification);
}

Here is how i handle the intent

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    var id = intent.GetStringExtra("id");

    Task.Factory.StartNew(async () => {
        await download(id);
        StopForeground(false);
    });

    return StartCommandResult.NotSticky;
}

The download method must be async.

My problem here is that the service fires off fine, does the download(id) method fine, even if i close the app(This is what i wanted). But continues to work even after the call to StopForeground(false); .I don't need it to run afterward, since it will still consume resources, and the system won't kill it easily because it's a foreground service.

I could see that my the service running in Android Device Manager, and that my app is still running in debug in VS2015.

Any idea ? Is there any other way to kill the service ?

The stopForeground() method only stops the foreground state of the Service . And with false as the parameter it doesn't even remove the notification, which you probably want it to do, so you could switch that to true .

To make the Service stop itself you can call stopSelf() .

So your code could be something like:

Task.Factory.StartNew(async () => {
        await download(id);
        stopForeground(true);
        stopSelf();  
    });

(...unless there's some minor detail that I missed without actually running the code. But you get the basic idea anyway.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM