我写了一个应用程序来查找GPS坐标。该程序在Android 4.3和4.4.2上完全正常,但由于某种原因,它不适用于2.3.4和2.3.6。 GPS甚至没有打开。是否需要做一些额外的事情来使其与旧的API兼容?我在清单中包含了以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
这是代码:
package com.hari.gps;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
public static Context mContext;
public static Context getContext() {
return mContext;
}
public void setContext(Context mContext) {
MainActivity.mContext = mContext;
}
private LocationManager locationManager;
private String provider;
public static float lat, lng;
public static TextView t3, t4, t5, t6;
// SMSReceiver s;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.text1);
longitudeField = (TextView) findViewById(R.id.text2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
@Override
protected void onResume() {
super.onResume();
// s.onReceive(getApplicationContext(), getIntent());
//
// t3.setText(s.messageReceived);
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void msg(View view) {
EditText e1 = (EditText) findViewById(R.id.edit);
String phoneno = "8056371433";
String s = e1.getText().toString();
String message, m1, m2;
t3 = (TextView) findViewById(R.id.text3);
t4 = (TextView) findViewById(R.id.text4);
t5 = (TextView) findViewById(R.id.text5);
t6 = (TextView) findViewById(R.id.text6);
m1 = String.valueOf(lat);
m2 = String.valueOf(lng);
message = m1 + " " + m2;
if (e1.getText().length() == 0)
sendSMS(phoneno, message);
else
sendSMS(s, message);
}
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(MainActivity.this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(
MainActivity.this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
boolean flag1 = true, flag2 = true;
lat = (float) (location.getLatitude());
lng = (float) (location.getLongitude());
if (lng < 0) {
lng = -lng;
flag1 = false;
}
if (lat < 0) {
lat = -lat;
flag2 = false;
}
if (flag2)
latituteField.setText("Latitude = " + lat + " N" + "\n");
else
latituteField.setText("Latitude = " + lat + " S" + "\n");
if (flag1)
longitudeField.setText("Longitude = " + lng + " E");
else
longitudeField.setText("Longitude = " + lng + " W");
// deg = Math.abs((int) lat);
// min = (int) ((lat - (float) deg) * 60.0);
// sec = (int) ((((lat - (float) deg) * 60) - min) * 60);
// if (flag2)
// latituteField.setText("Latitude = " +String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'N'+"\n");
// else
// latituteField.setText("Latitude = " +String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'S'+"\n");
// deg = Math.abs((int) lng);
// min = (int) ((lng - (float) deg) * 60.0);
// sec = (int) ((((lng - (float) deg) * 60) - min) * 60);
// if (flag1)
// longitudeField.setText("Longitude = " + String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'E');
// else
// longitudeField.setText("Longitude = " + String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'W');
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
我不得不添加requestlocationupdates()以使其工作奇怪的是我没有在Jellybean和KitKat上使用上述功能而获得GPS坐标。所以修改后的代码是:
Criteria criteria = new Criteria();
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
答案 1 :(得分:0)
//start
public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener,com.google.android.gms.maps.GoogleMap.OnMapClickListener,OnMapLongClickListener,OnMarkerClickListener,GoogleMap.OnInfoWindowClickListener {
// Update interval in milliseconds for location services
private static final long UPDATE_INTERVAL = 5000;
// Fastest update interval in milliseconds for location services
private static final long FASTEST_INTERVAL = 1000;
// Google Play diagnostics constant
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Speed threshold for orienting map in direction of motion (m/s)
private static final double SPEED_THRESH = 1;
private static final String TAG = "Mapper";
private LocationClient locationClient;
private Location currentLocation;
private double currentLat;
private double currentLon;
private GoogleMap map;
private LatLng map_center;
private int zoomOffset = 5;
private float currentZoom;
private float bearing;
private float speed;
private float acc;
private Circle localCircle;
private double lon;
private double lat;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
// Define an object that holds accuracy and frequency parameters
LocationRequest locationRequest;
// Set up shared preferences to persist data. We will use it later
// to save the current zoom level if user leaves this activity, and
// restore it when she returns.
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get a handle to the Map Fragment
// map = ((MapFragment) getFragmentManager()
// .findFragmentById(R.id.mapme_map)).getMap();
map=((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.mapme_map)).getMap();
if(map != null){
// Set the initial zoom level of the map
currentZoom = map.getMaxZoomLevel()-zoomOffset;
// Add a click listener to the map
map.setOnMapClickListener(this);
// Add a long-press listener to the map
map.setOnMapLongClickListener(this);
// Add Marker click listener to the map
map.setOnMarkerClickListener(this);
// Add marker info window click listener
map.setOnInfoWindowClickListener(this);
} else {
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
/* Create new location client. The first 'this' in args is the present
* context; the next two 'this' args indicate that this class will handle
* callbacks associated with connection and connection errors, respectively
* (see the onConnected, onDisconnected, and onConnectionError callbacks below).
* You cannot use the location client until the onConnected callback
* fires, indicating a valid connection. At that point you can access location
* services such as present position and location updates.
*/
locationClient = new LocationClient(this, this, this);
// Create the LocationRequest object
locationRequest = LocationRequest.create();
// Set request for high accuracy
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set update interval
locationRequest.setInterval(UPDATE_INTERVAL);
// Set fastest update interval that we can accept
locationRequest.setFastestInterval(FASTEST_INTERVAL);
// Get a shared preferences
prefs = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
// Get a SharedPreferences editor
prefsEditor = prefs.edit();
// Keep screen on while this map location tracking activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
// Following two methods display and handle the top bar options menu for maps
// Save the current zoom level when going into the background
@Override
protected void onPause() {
// Store the current map zoom level
if(map != null){
currentZoom = map.getCameraPosition().zoom;
prefsEditor.putFloat("KEY_ZOOM",currentZoom);
prefsEditor.commit();
}
super.onPause();
Log.i(TAG,"onPause: Zoom="+currentZoom);
}
@Override
protected void onResume() {
super.onResume();
// Restore previous zoom level (default to max zoom level if
// no prefs stored)
if (prefs.contains("KEY_ZOOM") && map != null){
currentZoom = prefs.getFloat("KEY_ZOOM", map.getMaxZoomLevel());
}
Log.i(TAG,"onResume: Zoom="+currentZoom);
// Keep screen on while this map location tracking activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
/* The following two lifecycle methods conserve resources by ensuring that
* location services are connected when the map is visible and disconnected when
* it is not.
*/
// Called by system when Activity becomes visible, so connect location client.
@Override
protected void onStart() {
super.onStart();
locationClient.connect();
}
// Called by system when Activity is no longer visible, so disconnect location
// client, which invalidates it.
@Override
protected void onStop() {
// If the client is connected, remove location updates and disconnect
if (locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
}
locationClient.disconnect();
// Turn off the screen-always-on request
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onStop();
}
}