0

GPS 좌표를 찾기 위해 앱을 작성했습니다. 이 프로그램은 Android 4.3 및 4.4.2에서 완전히 작동하지만 몇 가지 이유로 2.3.4 및 2.3.6에서 작동하지 않습니다. GPS가 켜지지 않습니다. 이전 API와 호환되도록하기 위해 수행해야 할 추가 사항이 있습니까? 내가 매니페스트에 다음과 같은 권한을 포함했다 : GPS 프로그램은 JellyBean과 KitKat에서 작동하지만 진저 브레드에서는 작동하지 않습니다.

<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

코드를 게시했습니다 .. –

+0

onCreate의 getLastKnownLocation은 분명히 GPS 하위 시스템을 시작하지 않지만 onResume에서 위치 업데이트를 요청하고 있습니다. getBestProvider가이 시점에서 사용할 수없는 것을 반환 할 가능성이 있습니다. 네트워크 또는 gps 공급자를 하드 코딩하여 결과를 보았습니까? 개인적으로 나는 getbestprovider- 앱이 GPS를 필요로하는 경향이 있는지 (어떤 경우에는 그것을 사용 하는가) 그렇지 않은지 (배터리 사용을 위해 피하는 경우) 경향이있다. –

답변

0

내가 requestlocationupdates를 추가했다() 그것이 내가 얻고 있었다 이상한 일을 만들려면 GPS는 Jellybean 및 KitKat에서 상기 기능을 사용하지 않고 조정합니다. 그래서 수정 된 코드는 다음과 같습니다

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); 
0

// FragmentActivity가 GooglePlayServicesClient.ConnectionCallbacks를 구현 공용 클래스 MainActivity가 확장 시작 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(); 
} 
관련 문제