StartService方法已执行,但Service的事件未激发



我有一个活动,我在OnCreate方法中启动了一个服务。StartService方法执行时没有任何错误,但Service类中没有任何事件未被激发!正如您在我的代码中看到的,我测试了显式和隐式模式来启动服务,但两个结果都是一样的!我的代码:

活动:

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
serviceToStart = new Intent(ApplicationContext, typeof(TrackService));
StartService(serviceToStart);
}
catch(Exception e)
{
var ee = e;
}
}

轨道服务:

[Service(IsolatedProcess = true, enabled = true)]
public class TrackService : Service
{
FusedLocationProviderClient fusedLocationProviderClient;
public override void OnCreate()
{
base.OnCreate(); //Break point set here
}
public override StartCommandResult OnStartCommand(Android.Content.Intent
intent, StartCommandFlags flags, int startId)
{
fusedLocationProviderClient = 
LocationServices
.GetFusedLocationProviderClient(this); //Break point set here
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}

清单:

编辑:清单手册删除删除

有人能告诉我出了什么问题吗?

请在清单文件中提及您的服务。这是非常重要的一步,因为如果没有清单服务条目,您的服务类就永远不会启动。

下面的代码行非常重要,这应该在您的清单文件中。

<service android:name=".TrackService" android:enabled="true"></service>

有关服务的更多说明,请参阅以下链接-https://developer.android.com/training/run-background-service/create-service

1(允许ServiceAttribute(和构建过程(属性设置清单条目,无需手动更改:

[Service(IsolatedProcess = true, enabled = true)]

注意:如果您希望/需要手动更改清单,则需要将ServiceAttribute中的Name分配给硬编码一个完全限定的包和Java类名,然后可以在清单中使用

2( 启动服务时,使用应用程序上下文和服务的C#类型构建意图:

var serviceIntent = new Intent(ApplicationContext, typeof(TrackService));
StartService(serviceIntent);

终于来了!我找到了问题的根源!然而,我不知道为什么会发生这种情况,我该如何解决!

我总是在logcat中得到这个错误:

未找到void mono.android.Runtime.register 的实现

在逐个删除代码后,我发现问题是由IsolatedProcess属性引起的。只要删除它,代码就可以很好地工作。

注意:正如您所看到的,没有必要为服务设置enabled属性。

[Service]
public class TrackService : Service

最新更新