0

我承认我对 android 比较陌生,我来自 python 和 C++。帮助将不胜感激。我只是从广播接收器 onReceive 调用位置更新,这样我就可以给我的设备发短信并接收它的位置,在那个时刻更新。

我发现我可以调用位置来发送文本,但它不会更新位置,它只是给出最后一次知道的。如果我两次调用 requestLocationUpdates,它似乎使用设备上的 GPS 图标进行定位,但是对 requestLocationUpdates 的第二次调用不使用更新的位置,它使用的是旧位置。如果我不调用 requestLocationUpdates 两次,它甚至不会更新(并且没有 GPS 图标闪烁确认这一点。)这是我的代码,对 requestLocationUpdates 的第一个冗余调用被注释掉了。
我知道代码不是很漂亮(就像 Thread.sleep 一样,我打算在更新工作后将其删除。请原谅那些临时位。有人可以帮助我吗,代码应该在逻辑上做我想要的,但是逻辑似乎不适用于这个..:

package com.JT.appNew01;
import java.util.ArrayList;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
public class SmsReceiverXxx extends BroadcastReceiver{
    public static final String COMMAND = "SENDER";
    public static final int SENDER_ACT_DOCUMENT = 0;
    public static final int SENDER_SRV_POSITIONING = 1;
    public static final int MIN_TIME_REQUEST = 5 * 1000;
    public static final String ACTION_REFRESH_SCHEDULE_ALARM =
            "com.JT.appNew01.ACTION_REFRESH_SCHEDULE_ALARM";
    private static Location currentLocation;//was private static
    private static Location prevLocation;//was private static
    private static Context _context;
    private String provider = LocationManager.GPS_PROVIDER;
    private static Intent _intent;
    private static LocationManager locationManager;//was private static
    //I ADDED FOR FIRST PASS THE FOLLOWING:
    private LocationListener locList=new LocationListener(){
        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            try {
                gotLocation(location);
            } catch (Exception e) {
            }
        }
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }
        @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
            try {
                String strStatus = "";
                switch (status) {
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    strStatus = "GPS_EVENT_FIRST_FIX";
                    break;
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    strStatus = "GPS_EVENT_SATELLITE_STATUS";
                    break;
                case GpsStatus.GPS_EVENT_STARTED:
                    strStatus = "GPS_EVENT_STARTED";
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    strStatus = "GPS_EVENT_STOPPED";
                    break;
                default:
                    strStatus = String.valueOf(status);
                    break;
                }
            } catch (Exception e) {
                                e.printStackTrace();
            }
        }
        };// I ADDED THIS TO GO WITH FIRST PASS!!!!!
    private static LocationListener locationListener = new LocationListener(){//was private static
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            try {
                String strStatus = "";
                switch (status) {
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    strStatus = "GPS_EVENT_FIRST_FIX";
                    break;
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    strStatus = "GPS_EVENT_SATELLITE_STATUS";
                    break;
                case GpsStatus.GPS_EVENT_STARTED:
                    strStatus = "GPS_EVENT_STARTED";
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    strStatus = "GPS_EVENT_STOPPED";
                    break;
                default:
                    strStatus = String.valueOf(status);
                    break;
                }
            } catch (Exception e) {
                                e.printStackTrace();
            }
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(Location location) {
            try {
                gotLocation(location);
            } catch (Exception e) {
            }
        }
    };
        @Override
        public void onReceive(final Context context, Intent intent) 
        {
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            String valuephn=sharedPrefs.getString("welcome_message", "NULL");
            int zz = 0;
            int MAX_SMS_MESSAGE_LENGTH = 160; 
            Bundle bundle = intent.getExtras();        
            SmsMessage[] msgs = null;
            String str = "";    
            Object[] pdus = (Object[]) bundle.get("pdus"); 
            msgs = new SmsMessage[pdus.length];
            if (bundle != null)
            {
              try {
                for (int i=0; i<msgs.length; i++){
                    msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                    str += "Map Trax - Location: " + msgs[i].getOriginatingAddress();                     
                    str += " :";
                    str += msgs[i].getMessageBody().toString();
                    str += "\n";   
                    zz=i;
                }
                   } catch (Exception e){
                         e=e;
                     }
                SmsManager sms = SmsManager.getDefault();
                PendingIntent pendingIntent = null;
                //String xyzx = msgs[zz].getOriginatingAddress();
                String xyzx="a";             // TEMPORARY FOR SKYPE!!! USE LINE ABOVE!!!
                // FIRST PASS TRY TO GET COORDS:
                //try{
                //  //if ( xyzx.contains(valuephn) ) {
                //  if ( xyzx.contains("a") ) {                // TEMPORARY FOR SKYPE!!! USE LINE ABOVE!!!
                //      _context = context;
                //      _intent = intent;
                //      locationManager = (LocationManager) context
                //              .getSystemService(Context.LOCATION_SERVICE);
                //      if (locationManager.isProviderEnabled(provider)) {
                //          locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
                //                  5, locList);            
                //         
                //          Location gotLoc = locationManager.getLastKnownLocation(provider);
                //          gotLocation(gotLoc);
                //          pauseOne();
                //          pauseTwo();
                //          pauseThree();
                //          pauseFour();
                //          pauseFive();
                //          pauseOne();
                //          pauseTwo();
                //          pauseThree();
                //          pauseFour();
                //          pauseFive();
                //          pauseOne();
                //          pauseTwo();
                //          pauseThree();
                //          pauseFour();
                //          pauseFive();
                //          OnNewLocationReceived(gotLoc);//JUST ADDED!!!
                //          stopLocationListener();//JUST ADDED!!!
                //         
                //
                //      } else {
                //          Location gotLoc2 = locationManager.getLastKnownLocation(provider);
                //          pauseOne();
                //          pauseTwo();
                //          pauseThree();
                //          pauseFour();
                //          pauseFive();
                //          pauseOne();
                //          pauseTwo();
                //          pauseThree();
                //          pauseFour();
                //          pauseFive();
                //          pauseOne();
                //          pauseTwo();
                //          pauseThree();
                //          pauseFour();
                //          pauseFive();
                //          OnNewLocationReceived(gotLoc2);//JUST ADDED!!!
                //          stopLocationListener();//JUST ADDED!!!
                //      }
                //  }}catch(Exception zzz){}
                // END FIRST PASS.
                try{
                //if ( xyzx.contains(valuephn) ) {
                if ( xyzx.contains("a") ) {                // TEMPORARY FOR SKYPE!!! USE LINE ABOVE!!!
                    _context = context;
                    _intent = intent;
                    locationManager = (LocationManager) context
                            .getSystemService(Context.LOCATION_SERVICE);
                    if (locationManager.isProviderEnabled(provider)) {
                        locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
                                5, locationListener);           

                        Location gotLoc = locationManager.getLastKnownLocation(provider);
                        gotLocation(gotLoc);
                        pauseOne();
                        pauseTwo();
                        pauseThree();
                        pauseFour();
                        pauseFive();
                        pauseOne();
                        pauseTwo();
                        pauseThree();
                        pauseFour();
                        pauseFive();
                        pauseOne();
                        pauseTwo();
                        pauseThree();
                        pauseFour();
                        pauseFive();
                        OnNewLocationReceived(gotLoc);//JUST ADDED!!!
                        stopLocationListener();//JUST ADDED!!!
                    } else {
                        Location gotLoc2 = locationManager.getLastKnownLocation(provider);
                        pauseOne();
                        pauseTwo();
                        pauseThree();
                        pauseFour();
                        pauseFive();
                        pauseOne();
                        pauseTwo();
                        pauseThree();
                        pauseFour();
                        pauseFive();
                        pauseOne();
                        pauseTwo();
                        pauseThree();
                        pauseFour();
                        pauseFive();
                        OnNewLocationReceived(gotLoc2);//JUST ADDED!!!
                        stopLocationListener();//JUST ADDED!!!
                    }
                //sms.sendTextMessage(valuephn,"", "Map Trax - GPS Co-ordinates:"+locationStringFromLocation(null).toString()+" - Map: http://maps.google.com/?q="+locationStringFromLocation(null).toString(),pendingIntent,pendingIntent);
                    Toast.makeText(context, "1: "+locationStringFromLocation(null).toString(), Toast.LENGTH_SHORT).show();
                    locationManager.removeUpdates(locationListener);
                }
                }catch(Exception zzz){
                    try{
                        if ( xyzx.contains("a") ) {
                            //sms.sendTextMessage(valuephn,"", "Map Trax - GPS Co-ordinates:"+locationStringFromLocation2(null).toString()+" - Map: http://maps.google.com/?q="+locationStringFromLocation2(null).toString(),pendingIntent,pendingIntent);
                            Toast.makeText(context, "2: "+locationStringFromLocation2(null).toString(), Toast.LENGTH_SHORT).show();
        locationManager.removeUpdates(locationListener);
                           }
                    }catch(Exception zzzz){
                        //sms.sendTextMessage(valuephn,"","Location currently unavailable",pendingIntent,pendingIntent);
                        Toast.makeText(context, "Location currently unavailable", Toast.LENGTH_SHORT).show();
                        locationManager.removeUpdates(locationListener);
                    }
                }
                };
        }
        private void pauseFive() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        private void pauseFour() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        private void pauseThree() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        private void pauseTwo() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        private void pauseOne() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static String locationStringFromLocation(final Location location) {//was public static
            return String.format("%.3f,%.3f", currentLocation.getLatitude(), currentLocation.getLongitude());
        }
        public static String locationStringFromLocation2(final Location location) {//was public static
            return String.format("%.3f,%.3f", prevLocation.getLatitude(), prevLocation.getLongitude());
        }
        private static void gotLocation(Location location) {//was public static
            prevLocation = currentLocation == null ?
                    null : new Location(currentLocation);
            currentLocation = location;
            if (isLocationNew()) {
                OnNewLocationReceived(location);
                //Toast.makeText(_context, "new location saved", Toast.LENGTH_SHORT)
                //        .show();
                stopLocationListener();
            }
        }
        private static boolean isLocationNew() {//was public static
            if (currentLocation == null) {
                return false;
            } else if (prevLocation == null) {
                return true;
            } else if (currentLocation.getTime() == prevLocation.getTime()) {
                return false;
            } else {
                return true;
            }
        }
        public static void stopLocationListener() {//was public static
            locationManager.removeUpdates(locationListener);
        }
        static ArrayList<OnNewLocationListener> arrOnNewLocationListener =
                new ArrayList<OnNewLocationListener>();
        public static void setOnNewLocationListener(
                OnNewLocationListener listener) {
            arrOnNewLocationListener.add(listener);
        }
        public static void clearOnNewLocationListener(
                OnNewLocationListener listener) {
            arrOnNewLocationListener.remove(listener);
        }
        // This function is called after the new point received
        private static void OnNewLocationReceived(Location location) {
            // Check if the Listener was set, otherwise we'll get an Exception when
            // we try to call it
            if (arrOnNewLocationListener != null) {
                // Only trigger the event, when we have any listener
                for (int i = arrOnNewLocationListener.size() - 1; i >= 0; i--) {
                    arrOnNewLocationListener.get(i).onNewLocationReceived(
                            location);
                }
            }
        }
}

4

1 回答 1

1

You have to write a service to update location and start that service when your broadcast receiver received the Sms.

BroadcastReceiver document

Receiver Lifecycle

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

于 2013-04-13T18:09:50.947 回答