Android吐司没有显示

时间:2013-07-04 09:04:55

标签: android android-location

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

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。我使用geo fix来更改位置。我实现了LocationListener的其他方法,但它们都是空的。显示电话号码的祝酒词工作正常。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

一个建议:

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

  

选择尽可能高的时间值。

答案 1 :(得分: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();
    }