如何在MyService中获得更好的位置准确性

时间:2016-01-11 22:14:54

标签: android service

所以我的问题是MyService无法正常工作已经解决了......大多数情况下。我首先使用以下定位方法获得了MainActivity(从代码中删除了不重要的东西):

public class MainActivity extends Activity implements LocationListener{   

    private Context context;

    LocationManager locationmanager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        context=this;

        Intent intent = new Intent(this, MyService.class);
        startService(intent);

        Button button2 = (Button)findViewById(R.id.button2);

        // Things that matter for this question below:

        locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria cri = new Criteria();
        String provider = locationmanager.getBestProvider(cri, false);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},0);
        }

        if (provider != null) {
            Location location = locationmanager.getLastKnownLocation(provider);
            locationmanager.requestLocationUpdates(provider, 60000, 0, this); //original (provider,minimalTime,minimalDistance,this); (provider,1800000,0,this) = 30 minutes; 0 distance change

            if (location != null) {
                onLocationChanged(location);
            } else {
                Toast.makeText(getApplicationContext(), "location not found", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Provider is null", Toast.LENGTH_LONG).show();
        }

    }

我之前的问题,为MyService提供了“另一种”位置方法:

public class MyService extends Service {

    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;
    private double longitude;
    private double latitude;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //Here you get lat and long
        try {
            LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            longitude = location.getLongitude();
            latitude = location.getLatitude();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

       // alarm below (not showed)

我在MainActivity中的第一种方法,当连接到WIFI时,精度为30米或1030米(约50%的时间)。然而,使用MyService中的第二种方法,观察到1030米或更高的精度。我不确定,但它是提供者类型或具有ACCES_FINE_LOCATION类型的东西。

感谢。

0 个答案:

没有答案