我目前正在Android中编写一个与GPS配合使用的应用程序.目前我能够确定GPS是否已启用.我的问题是,如果禁用,我想在应用启动时启用GPS.我怎么能这样做程序化?此外,我想创建打开和关闭GPS的功能,我读取stackoverflow上关于它的所有线程然而我尝试的所有功能我得到"不幸的是你的应用程序必须停止"(我没有忘记添加权限)
有人可以帮助我使用启用或禁用GPS的工作功能吗?
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Run Code Online (Sandbox Code Playgroud)
起初,我使用了这些功能:
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用:
ENABLE GPS:
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
DISABLE GPS:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)
两者都不适合我
谁有想法?
您无法以编程方式打开和关闭GPS.您可以做的最好的事情是将用户发送到允许他们自己完成的设置屏幕.
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)
存在以编程方式打开/关闭GPS的黑客攻击,但它们仅适用于旧版本的Android.即使你可以,也不要这样做.用户可能已关闭GPS,因为他们不希望允许应用程序精确跟踪它们.尝试强制改变他们的决定是非常糟糕的形式.
如果您需要启用GPS,请在应用启动时检查并在用户无法启用时保释.
| 归档时间: |
|
| 查看次数: |
10912 次 |
| 最近记录: |