0

我正在尝试制作一个简单的应用程序,其中用户单击一个按钮,一些文本视图显示有关手机的各种信息(型号、电池百分比、位置、信号强度等)。我无法获取当前的纬度和经度,因为当我按下按钮时,textview 显示以前的纬度/经度(第一次显示 0,0,第二次显示我第一次按下它时的位置)。

我想要实现的是当我按下按钮时,激活位置管理器和位置监听器,并使 onClick() 方法等到纬度不等于旧纬度。我已经尝试过线程、处理程序和异步任务,但我没有管理任何东西。有小费吗?这就是我的 onClick() 方法现在的样子:(Infogatherer 是一个我收集所有信息的类)

    @Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.bMeasurements:

        oldLat=InfoGatherer.getLatitude();
        oldLong=InfoGatherer.getLongitude();

            //SOMEWHERE HERE START A THREAD OR SOMETHING IN ORDER TO RETRIEVE CURRENT LOCATION
        //Retrieval and Assignment of information to the corresponding text fields
        DeviceName.setText(infogatherer.getDeviceName());

        NetworkOp.setText(infogatherer.getNetworkOp());

        Date.setText(infogatherer.getDate());

        BatteryStatus.setText(String.valueOf(infogatherer.getBatteryStatus()));

        Generation.setText(String.valueOf(infogatherer.getGeneration()));   
        infogatherer.getLocation();
        Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
        infogatherer.getSignalStrength();
        SignalStrength.setText(String.valueOf(infogatherer.getDbm()));

        oldLat = InfoGatherer.getLatitude();
        oldLong = InfoGatherer.getLongitude();
        break;

    }

这是我的 InfoGatherer 课程:

package com.example.netmap;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.CellInfoGsm;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;

public class InfoGatherer extends Application{

    String address,city,country;
    int cid,lac,generation=0,ipAddress=0,signalStrngth=0;
    private GsmCellLocation location;
    private WifiInfo wifiInfo;
    private LocationManager lm;
    private LocationListener ll;
    Geocoder geoc;
    static public double Longitude,Latitude=0;
    List<Address> addresses;
    Context context;
    Intent batteryIntent;
    TelephonyManager tm;
    WifiManager wifimanager;

    public InfoGatherer(){

    }
    public InfoGatherer(Context context){
        this.context = context;
    }

    public String getDate(){
        Calendar c = Calendar.getInstance();
        return Integer.toString(c.get(Calendar.DAY_OF_MONTH))+"-"+Integer.toString(c.get(Calendar.MONTH))+"-"+Integer.toString(c.get(Calendar.YEAR))+"    "+Integer.toString(c.get(Calendar.HOUR_OF_DAY))+":"+Integer.toString(c.get(Calendar.MINUTE))+":"+Integer.toString(c.get(Calendar.SECOND));
    }

    public String getDeviceName(){
        return Build.MANUFACTURER +" "+Build.MODEL;
    }

    public String getNetworkOp(){
        tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getNetworkOperatorName();

    }

    public float getBatteryStatus() {
        batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        return ((float)batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) / (float)batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)) * 100.0f;
    }


    public int getGeneration(){
        tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getNetworkType();
    }

     public int getCid(){
        tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        location = (GsmCellLocation)tm.getCellLocation();
        return location.getCid();
    }

    public int getLac(){
        tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        location = (GsmCellLocation)tm.getCellLocation();
        return location.getLac();
    }

    public String getIpAddress() {
        // TODO Auto-generated method stub
        wifimanager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        wifiInfo = wifimanager.getConnectionInfo();
        ipAddress = wifiInfo.getIpAddress();
        return String.format("%d.%d.%d.%d",(ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
    }

    public void getLocation(){
        /*Criteria c = new Criteria();
        c.setAccuracy(Criteria.ACCURACY_FINE);
        c.setPowerRequirement(Criteria.POWER_LOW);
        String provider = lm.getBestProvider(c, true);*/

        lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        ll = new mylocationlistener();

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

    }

    public class mylocationlistener implements LocationListener{

        @Override
        public void onLocationChanged(android.location.Location location) {
            // TODO Auto-generated method stub
            if(location!=null){
                Longitude = location.getLongitude();
                Latitude = location.getLatitude();

                lm.removeUpdates(ll);

            }

        }



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

            //Pass views as parameters? DIscuss
            //DeviceName.setText(String.valueOf(Latitude) +" "+String.valueOf(Longitude));

        }

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

        }

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
            // TODO Auto-generated method stub

        }

    }

    public void getSignalStrength(){
        tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        PhoneStateListener Listener = new phoneStateListener();
        tm.listen(Listener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    public class phoneStateListener extends PhoneStateListener{
        public void onSignalStrengthsChanged(SignalStrength signalStrength){
            super.onSignalStrengthsChanged(signalStrength);
            if (signalStrength.isGsm()) {
                signalStrngth = -113 + 2 * signalStrength.getGsmSignalStrength();

            }
            else
                signalStrngth = -113 + 2 * signalStrength.getCdmaDbm();
        }

    }





    static public double getLatitude(){
        return Latitude;
    }

    static public double getLongitude(){
        return Longitude;
    }

    public String getAddress(){
        return address;
    }

    public String getCity(){
        return city;
    }

    public String getCountry(){
        return country;
    }

    public int getDbm(){
        return signalStrngth;
    }

}
4

3 回答 3

0

您没有提供足够的时间让位置服务获取位置。您在有时间打电话
之前询问纬度和经度。 LocationManageronLocationChanged

infogatherer.getLocation();
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));

调用infogatherer.getLocation();onClick 事件。在活动onResume()事件中执行此操作。从中
删除。在活动事件中 调用它。lm.removeUpdates(ll);onLocationChangedonPause()

如果您想查看此示例如何创建GPS 管理器类

编辑
尝试这样的事情:注意:未经测试!

private void updateLocationText(double oldLat, double oldLong) {
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        public void run() {
            boolean isPositionChanged = false;
            double lat;
            double long;
            while (!isPositionChanged) {  
                lat = InfoGatherer.getLatitude();
                long = InfoGatherer.getLongitude();
                if(lat != oldLat || long != oldLong)isPositionChanged = true;
            }
            handler.post(new Runnable(){
                public void run() {
                    Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
                });
            }
        }
    };
    new Thread(runnable).start();
}  

请注意,如果您在没有更改位置的情况下单击该按钮,它将永远运行。

再次编辑

另一种更干净的方法:

代替

Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));  

有了这个

Location.postDelayed(new Runnable() {
    @Override
    public void run() {
        Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));
        Location.postInvalidate();//Try without, may be not necessary
    }
}, 3000);//Change if need
于 2013-10-23T18:00:22.507 回答
0

从应用程序中创建 LocationListener。在 Ativity 实例化类中,覆盖 onLocationChanged 事件并在那里更新 Location TextView。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

    listener = new MyLocationListener(){
        @Override
        public void onLocationChanged(android.location.Location location) {
            if(location!=null){
                Location.setText(String.valueOf(location.getLatitude()+","+location.getLatitude()));
                lm.removeUpdates(listener);
            }
        }
    }
}  

在 onClick() 事件中替换:

infogatherer.getLocation();
Location.setText(String.valueOf(InfoGatherer.getLatitude()+","+InfoGatherer.getLatitude()));

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
于 2013-10-24T09:57:14.463 回答
0

最后我使用了 AsyncTask,它帮助我在寻找位置时让应用程序休眠。

private class LocationThread extends AsyncTask<Context, Void, Void> {

    protected void onPreExecute() {
        infogatherer.startLocationListener();
    }

    @Override
    protected Void doInBackground(Context... params) {
        while (!infogatherer.getGo()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    protected void onPostExecute(final Void unused) {
        //Do whatever you wanna do after you get location
    }
}

getGo 是一个布尔值,只要它变为真,就会返回位置

public class mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(android.location.Location location) {
        if(location != null){
            Longitude = location.getLongitude();
            Latitude = location.getLatitude();
            lm.removeUpdates(ll);
            go = true;
        }
    }

希望您了解程序。干杯。

于 2014-05-01T12:29:09.997 回答