【问题标题】:Unexpectedly crashing of service when activity is stopped in Xamarin Android在 Xamarin Android 中停止活动时服务意外崩溃
【发布时间】:2017-08-10 15:26:12
【问题描述】:

我启动服务并创建新线程(下载大文件)。当我的活动打开应用程序正常工作 - 下载第一部分,第二部分,第三部分等。可以在电影中看到:https://youtu.be/qVItEjR00UY

但是当我关闭我的活动时,我的应用程序意外崩溃(不是立即而是在一段时间后):https://youtu.be/-Pe-vNgAy1U

为什么?当我从 Visual Studio 运行应用程序时,我遇到了同样的情况(没有错误消息)。

我的服务:

[Service]
class DownloadsService : Service
{
    DownloadsBroadcastReceiver receiver;
    Notification.Builder notificationBuilder;
    DownloadsData downloadsData;
    int uniqueNumber = 1000;
    bool isStarted;
    bool pauseTask;

    public override void OnCreate()
    {
        base.OnCreate();
        RegisterReceiver(receiver, new IntentFilter("com.xamarin.example.TEST"));
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        string downloadsDataToParse = intent.GetStringExtra("downloadsData");
        if (downloadsDataToParse != null)
            downloadsData = JsonConvert.DeserializeObject<DownloadsData>(downloadsDataToParse);
        pauseTask = intent.GetBooleanExtra("pauseTask", false);
        if (isStarted && !pauseTask)
            Log.Info("DAMIAN", "Usługa została już wcześniej uruchomiona");
        else if (isStarted && pauseTask)
        {
            PauseTask();
            Log.Info("DAMIAN", "Wstrzymano");
            UpdateNotification("Wstrzymano");
        }
        else
        {
            Log.Info("DAMIAN", "Usługa została uruchomiona");
            DispatchNotificationThatServiceIsRunning(downloadsData.Nazwa, "Rozpoczynanie");
            new Thread(new ThreadStart(() =>
            {
                MakeDownload(downloadsData.Zadania, downloadsData.Nazwa, downloadsData.AccountsList);
            })).Start();
            isStarted = true;
        }
        return StartCommandResult.Sticky;
    }

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

    public override void OnDestroy()
    {
        Log.Info("DAMIAN", "Usuwanie usługi");
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Cancel(uniqueNumber);
        isStarted = false;
        base.OnDestroy();
    }

    private void DispatchNotificationThatServiceIsRunning(string title, string content)
    {
        Intent stopIntent = new Intent(this, typeof(DownloadsBroadcastReceiver));
        stopIntent.PutExtra("action", "actionName");
        PendingIntent stopPi = PendingIntent.GetBroadcast(this, 4, stopIntent, PendingIntentFlags.UpdateCurrent);
        Intent intent = new Intent(this, typeof(MainActivity));
        TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
        stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
        stackBuilder.AddNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
        Notification.Action pauseAction = new Notification.Action.Builder(Resource.Drawable.Pause, "Wstrzymaj", stopPi).Build();
        Notification.Action removeAction = new Notification.Action.Builder(Resource.Drawable.Remove, "Usuń", resultPendingIntent).Build();
        notificationBuilder = new Notification.Builder(this)
            .SetSmallIcon(Resource.Drawable.Icon)
            .SetContentIntent(resultPendingIntent)
            .SetContentTitle(title)
            .SetContentText(content)
            .AddAction(pauseAction)
            .AddAction(removeAction);
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Notify(uniqueNumber, notificationBuilder.Build());
    }

    private void UpdateNotification(string content)
    {
        notificationBuilder.SetContentText(content);
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Notify(uniqueNumber, notificationBuilder.Build());
    }

    private void MakeDownload()
    {
        //download file
    }

    private void PauseTask()
    {
        //pause downloading
    }
}

【问题讨论】:

    标签: android xamarin android-activity service crash


    【解决方案1】:

    但是当我关闭我的活动时,我的应用程序意外崩溃(不是立即崩溃,而是在一段时间后)

    听起来您没有在活动关闭时取消绑定服务。请参考Bound Service Lifecycle

    尝试在您绑定服务的活动的OnStop()OnDestroy() 方法中取消绑定服务,例如:

    protected override void OnStop()
    {
        UnbindService(serviceConnection);
        base.OnStop();
    }
    

    或者

    protected override void OnDestroy ()
    {
            base.OnDestroy ();
    
            if (isBound) {
                    UnbindService (demoServiceConnection);
                    isBound = false;
            }
    }
    

    【讨论】:

    • 明白,但我想在我的活动关闭时运行服务。
    【解决方案2】:

    我用前台服务解决了这个问题。在OnStartCommand 我打电话给StartForeground(uniqueNumber, notification);,即使在活动结束后服务也能正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多