问题描述
我正在研究 xamarin.forms.(仅在 android 中面临以下问题)
I am working on xamarin.forms. (Facing below problem only in android)
当我的应用程序启动时,它会检查我的 GPS 位置是打开还是关闭.
When my application is started it checks my GPS location is on or off.
要打开或关闭 GPS 位置,我正在使用依赖服务.
To check GPS location on or off I am using dependency service.
public static bool CheckGPSConnection()
{
var gpsConnection = DependencyService.Get<IGPSConnectivity>();
return gpsConnection.CheckGPSConnection();
}
当我来到我的应用程序的主页时,我输入了以下代码
When I come to Home page of my application I put following code
if (Device.OS == TargetPlatform.Android)
{
if (!App.CheckGPSConnection())
{
bool answer = await DisplayAlert("Alert", "Would you like to start GPS?", "Yes", "No");
if (answer)
{
Android.App.Application.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings));
}
}
}
但它给了我一个例外
{Android.Util.AndroidRuntimeException: 从调用 startActivity()在 Activity 上下文之外需要 FLAG_ACTIVITY_NEW_TASK旗帜.这真的是你想要的吗?在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()[0x0000c] 在/Users/...}
我该怎么办?
推荐答案
这是特定于平台的功能,因此您应该为其创建一个 DependencyService.
This is platform specific functionality, so you should create a DependencyService for it.
就像为 IGPSConnectivity
创建另一个接口一样.例如 ISettingsService
.
Just like for the IGPSConnectivity
create another interface. For example ISettingsService
.
public interface ISettingsService
{
void OpenSettings();
}
然后在 Android 上,像这样实现它:
Then on Android, implement it like this:
public class SettingsServiceAndroid : ISettingsService
{
public void OpenSettings()
{
Xamarin.Forms.Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings));
}
}
现在再次从您共享的 PCL 代码中调用它,就像使用 GPS 连接一样.
Now call it from your shared PCL code, again, just like with the GPS connectivity one.
DependencyService.Get().OpenSettings();
因为您使用的是 DependencyService,所以将注入每个平台的正确实现.因此,不需要 if (Device.OS == TargetPlatform.Android)
行,除非您出于其他原因这样做.另外,我认为这种方法现在已弃用.从 Xamarin.Forms 2.3.4 开始,您现在应该使用 Device.RuntimePlatform == Device.Android
.
Because you are using the DependencyService, the right implementation per platform will be injected. So, there is no need for the if (Device.OS == TargetPlatform.Android)
line, unless you did that for another reason of course. Also, I think this method is now deprecated. You should now use Device.RuntimePlatform == Device.Android
as of Xamarin.Forms 2.3.4.
这篇关于如何从我们的应用程序在 xamarin.forms 中打开设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!