前台服务启动xamarin.form android时,应用在android 8.0上崩溃

时间:2019-03-06 08:51:49

标签: xamarin.forms

当我的应用程序进入后台时,我启动前台服务。那时,我进入设置页面,并将权限状态更改为“在相机上拒绝”。我的应用在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();
    }

}

}

任何人都可以帮助解决此问题。

0 个答案:

没有答案