我正在使用Xamarin Forms开发一个Android应用程序,该应用程序由一个界面以及一个后台服务组成。
关闭接口应用程序时,我还需要该服务也能正常工作。
如果我在服务中添加“ IsolatedProcess = true”,则图形界面仍然可以使用,但服务会崩溃。
我读了很多帖子,提供了可能的解决方案,但是它们不起作用。 (我尝试在发布模式下进行编译,还删除了“使用共享运行时”标志)。
我正在使用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”,该服务将起作用,但是当我关闭应用程序接口进程时,它将停止。
最佳答案
通过将属性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 Service与IsolatedProcess崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53169377/