手机重启后,“不幸的是,应用已停止”错误

时间:2019-04-02 11:29:11

标签: xamarin.forms

手机重新启动后,出现“不幸的是应用已停止”错误。我的手机是Oreo 8,但是另一台装有Nougat 7.1.1的手机在手机重启后也出现相同的错误。我将GitHub上的James Montemagnos的MyStepCounter绑定服务代码与VS 2017(Xamarin Cross-Platform App)中的一些更改结合使用。如果手机在重启后由于此错误而启动,则该应用程序可以正常工作,否则,它不会计算步骤并且无法在后台运行。如果我在“电话设置-常规-电池-省电排除”中检查了该应用程序,则在电话重启后它可以正常工作,并且它在后台计步,而无需在Oreo手机上启动该应用程序。但是另一部手机上没有节电设置的设置

BootReceiver.cs

                [BroadcastReceiver(Enabled = true, Exported = true, DirectBootAware = true)]
                [IntentFilter(new string[] { Intent.ActionBootCompleted, Intent.ActionLockedBootCompleted, "android.intent.action.QUICKBOOT_POWERON", "com.htc.intent.action.QUICKBOOT_POWERON" })]
                public class BootReceiver : BroadcastReceiver
                {
                    public override void OnReceive(Context context, Intent intent)
                    {
                        var stepServiceIntent = new Intent(context, typeof(StepService));
                        context.StartService(stepServiceIntent);
                    }
                }

StepServiceBinder.cs

       public class StepServiceBinder : Binder
{
    StepService stepService;
    public StepServiceBinder(StepService service)
    {
        this.stepService = service;
    }

    public StepService StepService
    {
        get { return stepService; }
    }
}

StepServiceConnection.cs

         public class StepServiceConnection : Java.Lang.Object, IServiceConnection
{
    MainActivity activity;

    public StepServiceConnection(MainActivity activity)
    {
        this.activity = activity;
    }

    public void OnServiceConnected(ComponentName name, IBinder service)
    {
        var serviceBinder = service as StepServiceBinder;
        if (serviceBinder != null)
        {
            activity.Binder = serviceBinder;
            activity.IsBound = true;
        }
    }

    public void OnServiceDisconnected(ComponentName name)
    {
        activity.IsBound = false;
    }
}

StepService.cs

  public class StepServiceConnection : Java.Lang.Object, IServiceConnection
{
    MainActivity activity;

    public StepServiceConnection(MainActivity activity)
    {
        this.activity = activity;
    }

    public void OnServiceConnected(ComponentName name, IBinder service)
    {
        var serviceBinder = service as StepServiceBinder;
        if (serviceBinder != null)
        {
            activity.Binder = serviceBinder;
            activity.IsBound = true;
        }
    }

    public void OnServiceDisconnected(ComponentName name)
    {
        activity.IsBound = false;
    }
}

StepService.cs

[Service(Enabled = true)]
[IntentFilter(new String[] { "com.PedometerApp.StepService" })]
public class StepService :  Service, ISensorEventListener, INotifyPropertyChanged
{
    private SensorManager sManager;
    private bool isRunning;
    private long stepsToday = 0;
    public bool WarningState
    {
        get;
        set;
    }

    public long StepsToday
    {
        get { return stepsToday; }
        set
        {
            if (stepsToday == value)
                return;

            stepsToday = value;
            OnPropertyChanged("StepsToday");
            Settings.CurrentDaySteps = value;
            MessagingCenter.Send<object, long>(this, "Steps", Settings.CurrentDaySteps);
        }
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        var alarmManager = ((AlarmManager)ApplicationContext.GetSystemService(AlarmService));
        var intent2 = new Intent(this, typeof(StepService));
        intent2.PutExtra("warning", WarningState);
        var stepIntent = PendingIntent.GetService(ApplicationContext, 200, intent2, PendingIntentFlags.UpdateCurrent);
        alarmManager.Set(AlarmType.Rtc, Java.Lang.JavaSystem
            .CurrentTimeMillis() + 1000 * 60 * 60, stepIntent);

        var warning = false;
        if (intent != null)
            warning = intent.GetBooleanExtra("warning", false);
        Startup();

        return StartCommandResult.Sticky;
    }



    public override void OnTaskRemoved(Intent rootIntent)
    {
        base.OnTaskRemoved(rootIntent);

        UnregisterListeners();
        var intent = new Intent(this, typeof(StepService));
        intent.PutExtra("warning", WarningState);
        ((AlarmManager)GetSystemService(AlarmService)).Set(AlarmType.Rtc, Java.Lang.JavaSystem
            .CurrentTimeMillis() + 500,
            PendingIntent.GetService(this, 201, intent, 0));
    }

    private void Startup(bool warning = false)
    {
        CrunchDates(true);

        if (!isRunning)
        {
            RegisterListeners();
            WarningState = warning;
        }

        isRunning = true;
    }

    public override void OnDestroy()
    {
        base.OnDestroy();
        UnregisterListeners();
        isRunning = false;
        CrunchDates();
    }

    void RegisterListeners()
    {
        sManager = GetSystemService(SensorService) as SensorManager;
        sManager.RegisterListener(this, sManager.GetDefaultSensor(SensorType.StepCounter), SensorDelay.Ui);
    }


    void UnregisterListeners()
    {
        if (!isRunning)
            return; 
        try
        {
            var sensorManager = (SensorManager)GetSystemService(Context.SensorService);
            sensorManager.UnregisterListener(this);

            isRunning = false;
        }
        catch (Exception ex)
        {

        }
    }

    StepServiceBinder binder;
    public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
    {
        binder = new StepServiceBinder(this);
        return binder;
    }

    public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
    {
        //do nothing here
    }

    public void AddSteps(long count)
    {
        if (lastSteps == 0)
        {
            lastSteps = count;
        }


        newSteps = count - lastSteps;


        if (newSteps < 0)
            newSteps = 1;
        else if (newSteps > 100)
            newSteps = 1;


        lastSteps = count;
        CrunchDates();

        Settings.TotalSteps += newSteps;

        StepsToday = Settings.TotalSteps - Settings.StepsBeforeToday;
    }

    long newSteps = 0;
    long lastSteps = 0;
    public void OnSensorChanged(SensorEvent e)
    {
        if (lastSteps < 0)
            lastSteps = 0;
        var count = (long)e.Values[0];
        WarningState = false;
        AddSteps(count);
    }

    private void CrunchDates(bool startup = false)
    {
        if (!Utils.IsSameDay)
        {

            var yesterday = Settings.CurrentDay;
            var dayEntry = StepEntryManager.GetStepEntry(yesterday);
            if (dayEntry == null || dayEntry.Date.DayOfYear != yesterday.DayOfYear)
            {
                dayEntry = new StepEntry();
            }

            dayEntry.Date = yesterday;
            dayEntry.Steps = Settings.CurrentDaySteps;



            Settings.CurrentDay = DateTime.Today;
            Settings.CurrentDaySteps = 0;
            Settings.StepsBeforeToday = Settings.TotalSteps;
            StepsToday = 0;
            try
            {
                StepEntryManager.SaveStepEntry(dayEntry);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error {0}", ex.Message);
            }

        }

        else if (startup)
        {
            StepsToday = Settings.TotalSteps - Settings.StepsBeforeToday;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string name)
    {
        if (PropertyChanged == null)
            return;

        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

}

0 个答案:

没有答案