0

我有一个使用用户位置的活动。这是我到目前为止编写的代码:

public class VolSaveLocation extends Activity implements LocationListener {

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                useLocation();    
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.volsavelocaction);

        LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

        TelephonyManager phoneManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNumber = phoneManager.getLine1Number();
        Toast.makeText(getApplicationContext(), phoneNumber, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null) {
            Toast.makeText(getApplicationContext(), "Location not null!", Toast.LENGTH_SHORT).show();
            Message msg = new Message();
            msg.what = 0;
            msg.obj = location;
            handler.sendMessage(msg);
        }
        else
            Toast.makeText(getApplicationContext(), "Location is null!", Toast.LENGTH_SHORT).show();
    }
}

问题是,onLocationChanged 方法中的 Toast 都没有显示。我正在使用地理修复来更改位置。我实现了 LocationListener 的其他方法,但它们是空的。显示电话号码的 toast 工作正常。有人可以帮我吗?

4

2 回答 2

0

oncreate 定义一个类似 getLocation() 的方法,并在该函数中编写以下代码

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);      
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    if(provider!=null && !provider.equals("")){
        Location location = locationManager.getLastKnownLocation(provider);         
        locationManager.requestLocationUpdates(provider, 40000, 1, this);
        if(location!=null) {
            onLocationChanged(location);
        } else {

        }
    }else{
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
    }
于 2013-07-04T09:47:00.360 回答
0

一个建议:

为Timeinterval(requestLocationUpdates() 的第二个参数)选择一个合理的值。延长电池寿命也很重要。每次位置更新都需要来自 GPS、WIFI、Cell 和其他无线电的电源。

选择尽可能高的时间值。

于 2013-07-04T09:39:52.757 回答