没有从线程接收位置数据 - java

我试图使用计时器每隔一段时间发送一次包含用户位置的短信。最初,我遇到了nullpointerexception,这是由于我犯了一个简单的错误。解决此问题后,一切似乎都运行良好。但是,它永远都无法获得我的位置,因此,持续发送的文本显示为“无法接收位置”。

我要问的是为什么它没有得到我的位置?我该如何解决该问题?

没有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

参考方案

在调用onLocationChanged()之前,您的LocationListener可能已被破坏。您的服务应实现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) {}
}

Java-搜索字符串数组中的字符串 - java

在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…

Java Scanner读取文件的奇怪行为 - java

因此,在使用Scanner类从文件读取内容时,我遇到了一个有趣的问题。基本上,我试图从目录中读取解析应用程序生成的多个输出文件,以计算一些准确性指标。基本上,我的代码只是遍历目录中的每个文件,并使用扫描仪将其打开以处理内容。无论出于何种原因,扫描程序都不会读取其中的一些文件(所有UTF-8编码)。即使文件不是空的,scanner.hasNextLine()在…

Java Globbing模式以匹配目录和文件 - java

我正在使用递归函数遍历根目录下的文件。我只想提取*.txt文件,但不想排除目录。现在,我的代码如下所示:val stream = Files.newDirectoryStream(head, "*.txt") 但是这样做将不会匹配任何目录,并且返回的iterator()是False。我使用的是Mac,所以我不想包含的噪音文件是.DS_ST…

直接读取Zip文件中的文件-Java - java

我的情况是我有一个包含一些文件(txt,png,...)的zip文件,我想直接按它们的名称读取它,我已经测试了以下代码,但没有结果(NullPointerExcepion):InputStream in = Main.class.getResourceAsStream("/resouces/zipfile/test.txt"); Buff…

Java RegEx中的单词边界\ b - java

我在使用\b作为Java Regex中的单词定界符时遇到困难。对于text = "/* sql statement */ INSERT INTO someTable"; Pattern.compile("(?i)\binsert\b");找不到匹配项Pattern insPtrn = Pattern.compile(&…