【问题标题】:Not receiving location data from thread未从线程接收位置数据
【发布时间】:2012-10-19 22:42:44
【问题描述】:

我正在尝试使用计时器每隔一段时间发送包含用户位置的短信。最初,我遇到了一个空指针异常,这是由于我犯了一个简单的错误。一旦解决了这个问题,一切似乎都运行良好。但是,它永远不会获取我的位置,因此,不断发送的文本是“无法接收位置”。

我要问的是为什么它没有得到我的位置?我能做些什么来解决这个问题?

没有 logcat 错误,我正在使用两个模拟器来测试这个应用程序(将文本从一个发送到另一个)。如果您能提供任何帮助或解决方案,将不胜感激!如果我忽略了一些看似非常简单的事情,请提醒我我正在这样做。谢谢!

代码如下:

    public class MessageService extends Service{
int counter = 0;
private Timer timer = new Timer();
public String textTime, phoneNumber;
public int updateInterval;
int lat, lng;
String coordinates, latitude, longitude;
LocationManager locationManager;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    //receives the intent extras from the calling intent
    textTime = intent.getStringExtra("textTime");
    phoneNumber = intent.getStringExtra("phone");

    phoneNumber = "5556";

    //the following if statement has to do with transferring the string textTime into a number that can be used
    if (textTime.equals("15 Minutes")) {
        updateInterval = (15 * (60000));
    }else if (textTime.equals("30 Minutes")) {
        updateInterval = (30 * (60000));
    }else if (textTime.equals("1 Hour")){
        updateInterval = (60 * (60000));
    }else {
        updateInterval = (15 * (60000));
    }

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    new Thread(){
        public void run(){
            Looper.prepare();
            // Define a listener that responds to location updates
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                  // Called when a new location is found by the network location provider.
                  //makeUseOfNewLocation(location);
                    lat = (int) (location.getLatitude() * 1E6);
                    lng = (int) (location.getLongitude() * 1E6);

                    latitude = Integer.toString(lat);
                    longitude = Integer.toString(lng);

                    coordinates = "Coordinates: " + latitude + ", " + longitude + ". Latitude: " + latitude + " Longitude: " + longitude + ". Respond 'END' to stop texts."; 
                }

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

                public void onProviderEnabled(String provider) {}

                public void onProviderDisabled(String provider) {}
              };

              Looper.loop();

              if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
              }else{
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
              }

        }
    }.start();


    //the following method should use a timer to send a sms message in a timed interval. It also should implement using a different thread
    doSomethingRepeatedly();

    return START_STICKY;

}

public void doSomethingRepeatedly(){
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            //the following code should be what is done repeatedly
            //Log.d("MessageService", String.valueOf(++counter));

            sendSmsMessage();
        }
    }, 0, updateInterval);
}

//the following code handles sending the text message
public void sendSmsMessage(){
    SmsManager sms = SmsManager.getDefault();
    if (coordinates == null || coordinates.equals("")){
        coordinates = "Could Not Receive Location";
    }

    sms.sendTextMessage(phoneNumber, null, coordinates , null, null);

}

public void onDestroy() {
    super.onDestroy();

    if (timer != null) {
        timer.cancel();
    }
}




}//end of service

【问题讨论】:

标签: java android multithreading timer location


【解决方案1】:

您的 LocationListener 可能在调用 onLocationChanged() 之前已被销毁。您的服务应该实现 LocationListener 本身。


public class MessageService extends Service implements LocationListener {
    int counter = 0;
    private Timer timer = new Timer();
    public String textTime, phoneNumber;
    public int updateInterval;
    int lat, lng;
    String coordinates, latitude, longitude;
    LocationManager locationManager;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        //receives the intent extras from the calling intent
        textTime = intent.getStringExtra("textTime");
        phoneNumber = intent.getStringExtra("phone");

        phoneNumber = "5556";

        //the following if statement has to do with transferring the string textTime into a number that can be used
        if (textTime.equals("15 Minutes")) {
            updateInterval = (15 * (60000));
        }else if (textTime.equals("30 Minutes")) {
            updateInterval = (30 * (60000));
        }else if (textTime.equals("1 Hour")){
            updateInterval = (60 * (60000));
        }else {
            updateInterval = (15 * (60000));
        }

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }else{
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }

        //the following method should use a timer to send a sms message in a timed interval. It also should implement using a different thread
        doSomethingRepeatedly();

        return START_STICKY;

    }

    public void doSomethingRepeatedly(){
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                //the following code should be what is done repeatedly
                //Log.d("MessageService", String.valueOf(++counter));

                sendSmsMessage();
            }
        }, 0, updateInterval);
    }

    //the following code handles sending the text message
    public void sendSmsMessage(){
        SmsManager sms = SmsManager.getDefault();
        if (coordinates == null || coordinates.equals("")){
            coordinates = "Could Not Receive Location";
        }

        sms.sendTextMessage(phoneNumber, null, coordinates , null, null);

    }

    public void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        //makeUseOfNewLocation(location);
        lat = (int) (location.getLatitude() * 1E6);
        lng = (int) (location.getLongitude() * 1E6);

        latitude = Integer.toString(lat);
        longitude = Integer.toString(lng);

        coordinates = "Coordinates: " + latitude + ", " + longitude + ". Latitude: " + latitude + " Longitude: " + longitude + ". Respond 'END' to stop texts."; 
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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

【讨论】:

    【解决方案2】:

    我不太明白您的代码,但是如果您希望一个线程更新coordinates 字段,然后另一个线程读取coordinates 的内容,您需要使coordinates 字段@987654325 @。

    线程之间共享的任何值都需要同步或以某种方式跨越memory barrier 才能可见。

    【讨论】:

    • 是的,我试图在一个线程中更新变量,然后当计时器关闭时,它会发送带有相同变量的短信。那么,您的意思是,为了在线程之间使用变量,我只需要将其声明为 volatile 即可?让我试一试...
    • 我试过了,还是不行。我找到了原因,我必须让服务更新位置侦听器本身,否则,它在获取我的坐标之前就被破坏了。另一位用户指出了这一点,但他似乎出于某种原因删除了他的帖子。但我感谢你的帮助!我以前不知道 volatile 或如何使用它,谢谢!
    • @user1478764 我把我的答案放回去了,因为你一开始是这样想的,我认为我的答案很离谱......
    猜你喜欢
    • 1970-01-01
    • 2019-09-25
    • 2017-01-28
    • 1970-01-01
    • 2018-08-18
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多