我正在開發一個需要激活GPS的Android應用程序。如何在Android上打開GPS
我在很多論壇上閱讀了大量的話題,我已經找到了答案是:
這是不可能的
...但是...「地獄犬」 APP令我全球定位系統...所以...這是可能的!
任何人都可以幫助我嗎?
我正在開發一個需要激活GPS的Android應用程序。如何在Android上打開GPS
我在很多論壇上閱讀了大量的話題,我已經找到了答案是:
這是不可能的
...但是...「地獄犬」 APP令我全球定位系統...所以...這是可能的!
任何人都可以幫助我嗎?
不是不可能的,也不適合。你不能在沒有他的權力的情況下管理用戶的電話。
從Play商店:
「地獄犬自動開啓GPS,如果它是關閉的,當您試圖本地化設備(僅適用於Android 2.3.3 <),您可以防止未經授權的卸載 - 更多信息在應用程序配置中。「
你可以做這樣的事情:
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
曾經有一種漏洞允許GPS通過沒有特殊權限的應用程序啓動。這種利用不再存在於2.3(在大多數ROM中)。這裏還有一個貼子,討論它,
How can I enable or disable the GPS programmatically on Android?
「啓用GPS」是一個安全的環境,所以你必須有WRITE_SECURE_SETTINGS權限。然而,這是一個受保護的簽名權限,因此除非使用製造商的平臺證書籤名,否則您的應用將不會被授予此權限。
正確的做法是將用戶發送到位置設置頁面,並讓他們啓用GPS(如果他們希望的話)。例如,
Intent i = new
Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
你可能想看看這個線程
How can I enable or disable the GPS programmatically on Android?
這裏的代碼從線程
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);
}
}
複製但不建議使用該解決方案,因爲它不可用樂至Android版本> 2.3 supposingly ..做檢查的意見
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.gps_disabled_message)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
這將創建一個警告,讓用戶去設置屏幕和點擊後退按鈕,馬上就回來給你的應用程序。據我所知,電源插件的功能不能超過2.3。
使用此代碼 // turnGPSON調用後的setContentView(XML)
private void turnGPSOn() {
String provider = android.provider.Settings.Secure.getString(
getContentResolver(),
android.provider.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);
}
}**
我認爲我們有更多更好的版本,以使位置,而無需打開的設置就像谷歌地圖工程。
它將看起來是這樣的 -
的gradle中添加依賴關係 - 編譯 'com.google.android.gms:發揮服務地點:10.0.1'
public class MapActivity extends AppCompatActivity {
protected static final String TAG = "LocationOnOff";
private GoogleApiClient googleApiClient;
final static int REQUEST_LOCATION = 199;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setFinishOnTouchOutside(true);
// Todo Location Already on ... start
final LocationManager manager = (LocationManager) MapActivity.this.getSystemService(Context.LOCATION_SERVICE);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapActivity.this)) {
Toast.makeText(MapActivity.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
finish();
}
// Todo Location Already on ... end
if(!hasGPSDevice(MapActivity.this)){
Toast.makeText(MapActivity.this,"Gps not Supported",Toast.LENGTH_SHORT).show();
}
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapActivity.this)) {
Log.e("TAG","Gps already enabled");
Toast.makeText(MapActivity.this,"Gps not enabled",Toast.LENGTH_SHORT).show();
enableLoc();
}else{
Log.e("TAG","Gps already enabled");
Toast.makeText(MapActivity.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
}
}
private boolean hasGPSDevice(Context context) {
final LocationManager mgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null)
return false;
final List<String> providers = mgr.getAllProviders();
if (providers == null)
return false;
return providers.contains(LocationManager.GPS_PROVIDER);
}
private void enableLoc() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(MapActivity.this)
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("Location error","Location error " + connectionResult.getErrorCode());
}
}).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(MapActivity.this, REQUEST_LOCATION);
finish();
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
}
}
public class NearestActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
public static double gpsLat, gpsLong;
@Override
protected void onCreate(Bundle savedInstanceState) {
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onLocationChanged(Location location) {
mylocation = location;
if (mylocation != null) {
gpsLat = mylocation.getLatitude();
gpsLong = mylocation.getLongitude();
if(adapter.getItemCount()!=0) {
Collections.sort(list, new Comparator<TokoUpload>() {
@Override
public int compare(TokoUpload o1, TokoUpload o2) {
return o1.getMeter() - o2.getMeter();
}
});
adapter.notifyDataSetChanged();
}
}
}
@Override
public void onConnected(Bundle bundle) {
checkPermissions();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private void getMyLocation(){
if(googleApiClient != null) {
if (googleApiClient.isConnected()) {
int permissionLocation = ContextCompat.checkSelfPermission(NearestTokoActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
int permissionLocation = ContextCompat
.checkSelfPermission(NearestTokoActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(NearestTokoActivity.this,
REQUEST_CHECK_SETTINGS_GPS);
} catch (IntentSender.SendIntentException ignored) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
}
break;
}
}
private void checkPermissions(){
int permissionLocation = ContextCompat.checkSelfPermission(NearestTokoActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
}
}else{
getMyLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permissionLocation = ContextCompat.checkSelfPermission(NearestTokoActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
}
這裏的代碼 - [按Ø n或關閉GPS編程] [1] [1]:http://stackoverflow.com/questions/4721449/enable-gps-programatically-like-tasker – Rajkiran 2012-03-29 15:22:37
僅在機器人工作<2.3.3 – 2012-03-29 16:45:20