需要在url onLocationChanged方法上发送数据

时间:2015-09-28 11:59:08

标签: android android-fragments android-intent android-activity

我需要在url onLocationChanges方法上发送数据,我试图用以下代码完成任务,但是我得到错误,有人可以帮助我吗? 我的程序崩溃了以下代码

    @Override
    public void onLocationChanged(Location location) throws NetworkOnMainThreadException {
    txtLat = (TextView) findViewById(R.id.address_textview);
    txtLat.setText("Latitude:" + location.getLatitude() + ",         Longitude:"         +         location.getLongitude());

String strUrl="http://www.test.com/location.php?location="+location.getLatitude();
try {
    url = new URL(strUrl);
} catch (MalformedURLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
try {
    urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.connect();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    }

2 个答案:

答案 0 :(得分:0)

您无法在onLocationChanged()中执行网络I / O.您需要在Thread中开始后台onLocationChanged()。然后,后台Thread可以执行网络I / O.

答案 1 :(得分:0)

您可以在MainActivity.java类上编写以下代码&on;创建()

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);