我正在使用 Xamarin Forms 开发一个 Android 应用程序,它由一个界面和一个后台服务组成。 我需要该服务在界面应用程序关闭时也能正常工作。 如果我将“IsolatedProcess = true”添加到服务中,图形界面仍然有效,但服务崩溃了。 我阅读了很多可能的解决方案的帖子,但它们不起作用。 (我尝试在 Release模式下编译并删除“使用共享运行时”标志)。
我正在使用 Android 8.1 (Oreo) 作为目标框架进行编译。 目标环境为Android 4.2。
我在 MainActivity 类的 OnCreate 方法中启动服务:
Intent testIntent = new Intent(this.BaseContext, typeof(TestService));
StartService(testIntent);
服务类:
[Service(IsolatedProcess = true, Exported = true, Label = "TestService")]
public class TestService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
base.OnCreate();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Device.StartTimer(new TimeSpan(0, 0, 40), () =>
{
//Code executed every 40 seconds
});
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
}
public override bool StopService(Intent name)
{
return base.StopService(name);
}
}
如果我删除“IsolatedProcess = true”,该服务会工作,但当我关闭应用程序接口(interface)进程时它会停止。
最佳答案
我通过将属性 IsolatedProcess 的值更改为 true、删除 Device.StartTimer 指令并引入 BroadcastReceiver 解决了这个问题。
MainActivity 类:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static Intent testServiceIntent;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
testServiceIntent = new Intent(this.BaseContext, typeof(TestService));
LoadApplication(new App());
}
}
服务类:
[Service(IsolatedProcess = false, Exported = true, Label = "TestService")]
public class TestService : Service
{
System.Threading.Timer _timer;
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
base.OnCreate();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
businessLogicMethod();
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
}
public void businessLogicMethod()
{
//My business logic in a System.Threading.Timer
}
}
广播接收器类:
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class TestApplicationBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Log.Info("TestApp", "******* Loading Application *******");
try
{
if (intent.Action.Equals(Intent.ActionBootCompleted))
{
Intent service = new Intent(context, typeof(TestService));
service.AddFlags(ActivityFlags.NewTask);
context.StartService(service);
}
}
catch (Exception ex)
{
Log.Error("TestApp", "******* Error message *******: " + ex.Message);
}
}
}
我希望这对某人有用。
关于c# - Xamarin Forms 服务与 IsolatedProcess 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53169377/