首页 > 解决方案 > 当前台服务启动 xamarin.form android 时,应用程序在 android 8.0 上崩溃

问题描述

当我的应用程序进入后台时,我启动前台服务。那时我进入设置页面并将权限状态更改为拒绝相机。我的应用在 android 8.0 上崩溃了。

我的前台服务代码如下:

namespace MyProj.Droid.Services
{
[Service]
public class MyProjService : Service
{
    CancellationTokenSource _cts;
    private static ILogger logger = DependencyService.Get<ILogManager>().GetLog();
    public const string LOCATION_CHANNEL = "default";
    NotificationManager manager;
    NotificationCompat.Builder notification;
    public override void OnCreate()
    {
        base.OnCreate();
        manager = (NotificationManager)Forms.Context.GetSystemService("notification");
    }
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

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

        return StartCommandResult.Sticky;
    }

    void StartLocationServiceForeground()
    {
        try
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var chan1 = new NotificationChannel(LOCATION_CHANNEL,
                   new Java.Lang.String("Primary"), NotificationImportance.High);
                manager.CreateNotificationChannel(chan1);

                notification = new NotificationCompat.Builder(Forms.Context, LOCATION_CHANNEL);
                notification.SetOngoing(true)
                 .SetSmallIcon(Resource.Drawable.icon_transparent)
                 .SetContentTitle("MyProj 24x7 Trucker is running background")
                    .SetContentText("Tab for more information or to stop the app")
                    .SetColor(0x9c6114)
                         .SetPriority(NotificationCompat.PriorityHigh);
                StartForeground(1, notification.Build());
            }


        }
        catch(System.Exception ex)
        {

        }
    }


    public override void OnDestroy()
    {

        StopForeground(true);
        if (manager!=null)
        {
            manager.CancelAll();
        }
        base.OnDestroy();
    }

}

}

任何人都可以请帮助解决这个问题。

标签: xamarin.forms

解决方案


推荐阅读