Android 互联网连接可用时,从BoadCastereceiver发送纬度和经度

Android 互联网连接可用时,从BoadCastereceiver发送纬度和经度,android,Android,我想发送JSON字符串 { "latitude": 53.86898504, "longitude": 10.66561187, "time": "25.04.2015 11:37:11", "route": 4 } 每60秒发送一次到服务器,因此当我尝试从internet连接广播接收器发送JSON字符串时,JSON字符串在那里为空,但当我从onLocationChanged方法发送数据时,我在PostData类中获取字符串,但如果internet不可用,我希

我想发送JSON字符串

{
    "latitude": 53.86898504,
    "longitude": 10.66561187,
    "time": "25.04.2015 11:37:11",
    "route": 4
} 
每60秒发送一次到服务器,因此当我尝试从internet连接广播接收器发送JSON字符串时,JSON字符串在那里为空,但当我从onLocationChanged方法发送数据时,我在PostData类中获取字符串,但如果internet不可用,我希望在internet连接可用时发送数据如果可用,我将短时间存储字符串。如何实现它以在CONNECTIVITY\u ACTION BroadcastReceiver中获取JSONString

谢谢你的帮助

主要活动类别:

public class MainActivity extends ActionBarActivity {

Location location;
LocationManager locationManager;
String jSONString;

    TextView textJSON;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textJSON = (TextView) findViewById(R.id.textJSON);


        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new myLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);


    }

    private class BroadcastReceiverListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                     //code to get the strongest wifi access point in the JSON string the routes's value.
            }

            else if (intent.getAction().equals(
                    android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {

                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo netInfo = connectivityManager
                        .getActiveNetworkInfo();

                boolean isConnected = netInfo != null
                        && netInfo.isConnectedOrConnecting();
                if (isConnected) {
                    Toast.makeText(context,
                            "The device is connected to the internet ",
                            Toast.LENGTH_SHORT).show();
                if (location == null) {

                    Location locat = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (locat == null) {

                        LocationListener locLis = new myLocationListener();
                        LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        Criteria criteria = new Criteria();
                        Looper myLooper = Looper.myLooper();

                        locMan.requestSingleUpdate(criteria, locLis,
                                myLooper);

                    } else {
                        System.out.println("locat is not null");
                    }

                } else {
                    PostData sender = new PostData();
                    sender.timer(jSONString);
                    textJSON.setText(jSONString);
                }


                } else {
                    Toast.makeText(context,
                            "Please connect the device to the internet.",
                            Toast.LENGTH_SHORT).show();
                }

            }
        }

    }

    class myLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {

            if (location != null) {
                double pLong = location.getLongitude();
                double pLat = location.getLatitude();
                ...
                String time = sdf.format(location.getTime());

                jSONString = convertToJSON(pLong, pLat, time);
                System.out.println("The output of onLocationChanged: "+ jSONString);

                //The code works fine here. JSON string has its values here but in broadcastReceiver JSON string has null.
//              PostData sender = new PostData();
//              sender.timer(jSONString);
//              textJSON.setText(jSONString);



            }
        }
    }
}
希望这会有所帮助

  • 每当BroadCastReceiver触发时,首先检查
    位置
    (实例变量)是否为
    null
  • 如果
    location
    为空,则通过调用
    getLastKnownLocation(LocationManager.GPS\u PROVIDER)
    获取位置,返回位置或空值
  • 如果
    getLastKnownLocation()
    return
    null
    发出单个位置更新请求
    requestSingleUpdate(条件、位置侦听器侦听器、活套器)
    检查侦听器回调

  • 看起来,您可以通过添加一个额外的标志作为实例变量来确定是否在没有internet的情况下获得位置更新,并将
    isConnected
    标志作为实例变量来获得所需的行为

    如果连接到internet,则每次收到位置更改事件时都要发送位置数据,否则请设置标志并等到有internet连接时再发送上次位置更新的数据

    我在问题中使用了您的原始代码并对其进行了修改:

    public class MainActivity extends ActionBarActivity {
    
        int route_number;
        double pLong;
        double pLat;
        String time;
        String jSONString;
    
        boolean isConnected; //added
        boolean locationUpdatedNoInternet; //added
        long lastLocationTime = 0; //added
    
        TextView textJSON;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textJSON = (TextView) findViewById(R.id.textJSON);
    
    
            LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            LocationListener ll = new myLocationListener();
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);
    
    
        }
    
        private class BroadcastReceiverListener extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(
                        android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                    //code to get the strongest wifi access point in the JSON string the routes's value.
                }
    
                else if (intent.getAction().equals(
                        android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {
    
                    ConnectivityManager connectivityManager = (ConnectivityManager) context
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
    
                    NetworkInfo netInfo = connectivityManager
                            .getActiveNetworkInfo();
    
                    //set instance variable isConnected here instead of creating local variable
                    isConnected = netInfo != null
                            && netInfo.isConnectedOrConnecting();
                    //boolean isConnected = netInfo != null
                            //&& netInfo.isConnectedOrConnecting();
                    if (isConnected) {
                        Toast.makeText(context,
                                "The device is connected to the internet ",
                                Toast.LENGTH_SHORT).show();
    
                        //check if we got a location update with no internet
                        long currTime = System.currentTimeMillis();
                        if (locationUpdatedNoInternet == true) {
                            //check that last location send was longer than 5 seconds ago
                            if (lastLocationTime == 0 || ((currTime - lastLocationTime) > 5000 )){
                                lastLocationTime = System.currentTimeMillis(); //set last sent time
                                locationUpdatedNoInternet = false; //re-set to false
                                PostData sender = new PostData();
                                //since we are checking locationUpdatedNoInternet flag, we definitely have location data.
                                System.out.println("The output of internet broadcast: " + jSONString);
                                sender.timer(jSONString);
                                textJSON.setText(jSONString);
                            }
                        }
    
                    } else {
                        Toast.makeText(context,
                                "Please connect the device to the internet.",
                                Toast.LENGTH_SHORT).show();
                    }
    
                }
            }
    
        }
    
        class myLocationListener implements LocationListener {
    
            @Override
            public void onLocationChanged(Location location) {
    
                if (location != null) {
                    pLong = location.getLongitude();
                    pLat = location.getLatitude();
                    //...
                    time = sdf.format(location.getTime());
    
                    jSONString = convertToJSON(pLong, pLat, time);
                    System.out.println("The output of onLocationChanged: "+ jSONString);
    
                    long currTime = System.currentTimeMillis();
                    if (isConnected == true) {
                        //check that last location send was longer than 5 seconds ago
                        if (lastLocationTime == 0 || ((currTime - lastLocationTime) > 5000 )) {
                            //if connected, just send the data
                            lastLocationTime = System.currentTimeMillis(); //set last sent time
                            locationUpdatedNoInternet = false;
                            PostData sender = new PostData();
                            sender.timer(jSONString);
                            textJSON.setText(jSONString);
                        }
                    }
                    else{
                        //set flag so that the last location update will be sent once connection is established
                        locationUpdatedNoInternet = true;
                    }
    
                }
            }
        }
    }
    

    但在internet连接广播服务器中未定义位置。这是否意味着我将使用internet连接BroafdCastereceiver扩展myLocationListener,或者最好扩展我的PostData类?创建
    Location-Location
    的实例变量(类级别),并在
    onLocationChanged
    处初始化其值。当BroadCastReceiver为location实例而不是jsonString.please查看我的更新问题时,我按照您所说的那样暗示了它,并且我得到了以下错误:
    ,原因是:java.lang.NullPointerException:尝试调用虚拟方法'android.location.location.android.location.LocationManager.getLastKnownLocation(java.lang.String)'在空对象引用上
    使用前检查位置值
    if(location!=null){}
    我注意到在这里使用您的sulotion时,我得到了
    sender.timer(jSONString)的输出同时两次!?这是因为sender.timer(jSOnString)在
    BroadcastReceiverListener
    onLocationChanged()
    中被调用了两次吗?@MrAsker是的,这是可能的。如果是这样,您可以在日志中进行验证。一个简单的解决方案是保留上次更新时间的时间戳,并确保自上次更新以来时间已超过5秒。查看更新的答案,查看
    lastLocationTime
    currTime
    。请看一下这个问题