9

良い一日!私はユーザーの位置を監視するAndroidアプリに取り組んでいます。次の方法を使用して、LocationManagerを使用してユーザーの場所を取得しています

public void onLocationChanged(Location theLocation) {}

上記の方法により、ユーザーの移動があるたびに、位置座標を受け取ります。

しかし、今はアプリのログイン直後にユーザーの位置を取得することを計画しています。アプリの起動後に位置座標を手動で取得できるLocationManagerを使用する方法はありますか?

4

4 に答える 4

21

このテクニックを使用してください:

LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location location;

if(network_enabled){

   location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if(location!=null){
   longitude = location.getLongitude();
   latitude = location.getLatitude();
    }                
}

この場合、GPSを使用する必要はなく、モバイルネットワークのみが実行します。

マニフェストで次の許可を与えることを忘れないでください:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
于 2012-09-05T17:07:00.827 に答える
3

このコードを試してください。うまくいくことを願っています

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class MainActivity extends Activity implements LocationListener {

private LocationManager locationManager;
private String provider;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
      } else {
        System.out.println("Location not avilable");
      }

}

protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
  }

  /* Remove the locationlistener updates when Activity is paused */
  @Override
  protected void onPause() {
    super.onPause();
    locationManager.removeUpdates((LocationListener) this);
  }
public void onLocationChanged(Location location) {
    double lat = (double) (location.getLatitude());
    double lng = (double) (location.getLongitude());
    Toast.makeText(getApplicationContext(), lat+"----"+lng,Toast.LENGTH_LONG).show();
    Log.i("Latitude------------", "Lattitude:" +lat);
    Log.i("Longitude-------------", "Longitude:" +lng);
  }

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}
    }

必要な権限を追加する必要があります

于 2012-09-27T11:52:10.917 に答える
2

これが私がしたことです...1)mainactiviy.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button gpsButton = (Button) findViewById(R.id.getloc);

gpsButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
    LoadCoords();
}});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void LoadCoords(){
EditText locn = (EditText)findViewById(R.id.text1);
EditText locn1 = (EditText)findViewById(R.id.text2);
GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation){
Double latPoint=gps.getLatitude(); 
Double lngPoint =gps.getLongitude();   

locn.setText(latPoint.toString());
locn1.setText(lngPoint.toString());
}
}
}

別のファイル2)GPSTracker.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener{
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
    locationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    // getting network status
    isNetworkEnabled = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isGPSEnabled && !isNetworkEnabled) {
        // no network provider is enabled
    } else {
        this.canGetLocation = true;
        // First get location from Network Provider
        if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            if (locationManager != null) {
                location = locationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
            }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled) {
            if (location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("GPS Enabled", "GPS Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }
    }

} catch (Exception e) {
    e.printStackTrace();
}

return location;
}
public double getLatitude(){
if(location != null){
    latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */

public double getLongitude(){
if(location != null){
    longitude = location.getLongitude();
}

// return longitude
return longitude;
}
@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}



@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}

うまくいったら返信してください...

于 2013-03-03T19:24:45.213 に答える
0
    ActivityCompat.requestPermissions(MapsActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        /*
        tvLatitud.setText("No se tienen permisos");
        ...
         */

        return;
    }else
    {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude =  location.getLongitude();
    }
于 2019-01-31T15:54:17.333 に答える