Android服务已停止

时间:2019-01-27 14:45:32

标签: java android xamarin android-service background-process

我用Xamarin编写了一个Android应用程序。该应用程序执行一些长期运行的任务,向用户显示通知,并应在后台执行。据我所知,我应该为此使用Service。我创建了我的服务,这是它的代码:

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    base.OnStartCommand(intent, flags, startId);     

    var thread = new Thread(new Runnable(() => 
    {
        for (int i = 0; i < 10_000; i++)
        {
            ShowNotification("channel", "Search", $"second: {i}, threadId: {id} startId: {startId}");
            Thread.Sleep(1000);
        }                           
        StopSelf(startId);
    }));
    thread.Start();

    return StartCommandResult.StartSticky;
}

ShowNotification方法的代码:

protected void ShowNotification(string channel, string title, string message)
{
    Intent resultIntent = new Intent(this, GetType());
    resultIntent.AddFlags(ActivityFlags.NewTask);

    var resultPendingIntent = PendingIntent.GetActivity(this, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

    var mBuilder = new NotificationCompat.Builder(this);
    mBuilder.SetSmallIcon(Resource.Mipmap.ic_launcher)
        .SetContentTitle(title)
        .SetContentText(message)
        .SetAutoCancel(false)
        .SetContentIntent(resultPendingIntent);

    if (!(GetSystemService(NotificationService) is NotificationManager mNotificationManager))
        return;

    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        var importance = NotificationImportance.High;
        var notificationChannel = new NotificationChannel(channel, channel, importance);
        notificationChannel.EnableLights(true);
        notificationChannel.LightColor = Color.Red;
        notificationChannel.EnableVibration(true);
        notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
        mBuilder.SetChannelId(channel);
        mNotificationManager.CreateNotificationChannel(notificationChannel);
    }
    mNotificationManager.Notify(0, mBuilder.Build());
}

此代码有效,但是2-5分钟后服务停止并且不显示新的通知。是否可以禁止停止我的服务(或在停止后重新启动它)?我听说我应该从方法OnStartCommand返回标志START_STICKY并使用它。但是它不起作用,操作系统仍然会停止我的服务。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

SushiHangover已经说过,您必须在OnStartCommand()上致电startForeground() 当您启动服务器时,调用startForegroundService()