使用异步任务android

时间:2016-03-24 14:06:08

标签: java android

我正在尝试开发一个应用程序,通过http post定期向服务器发送位置。我在以下代码中尝试过异步任务。我是android编程的新手。当我运行此代码时,我收到错误“无法连接到/10.0.2.2(端口8080):连接失败:ETIMEDOUT(连接超时)”和“E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#1”。请帮帮我

package com.example.vikram.locationinterval;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownServiceException;
import java.nio.charset.Charset;
import java.security.Permission;


import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements LocationListener {
    protected LocationManager locationManager;

    TextView txtLat,content;
    protected static int intervalInMillis = 500;



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

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, intervalInMillis, 0.5f, this);
    }
    @Override
    public void onLocationChanged(Location location) {
        long now = System.currentTimeMillis();
        txtLat = (TextView) findViewById(R.id.textview1);
        txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude() + "\n now = " + now);
        try{

            System.out.println("\nTesting 2 - Send Http POST request");
            new MyAsyncTask(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude())).execute();
        }
        catch(Exception ex)
        {
            //System.out.println(ex.getCause());
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d("Latitude", "disable");
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d("Latitude","enable");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Latitude","status");
    }

    private class MyAsyncTask extends AsyncTask<String, Integer, Double> {

        protected String latitude,longitude;

        protected MyAsyncTask(String lat,String lon){
            this.latitude = lat;
            this.longitude = lon;
        }

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            try {
                postData(this.latitude, this.longitude);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Double result){

            Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
        }


        public void postData(String Lat,String Lon) throws UnsupportedEncodingException {
            // Create data variable for sent values to server

            String data = URLEncoder.encode("Latitude", "UTF-8")
                    + "=" + URLEncoder.encode(Lat, "UTF-8");

            data += "&" + URLEncoder.encode("Longitude", "UTF-8") + "="
                    + URLEncoder.encode(Lon, "UTF-8");
            System.out.println(data);

            String text = "";
            BufferedReader reader=null;



            // Send data
            try
            {

                // Defined URL  where to send data
                URL url = new URL("http://10.0.2.2:8080/GetSomeRest/webresources/service");

                // Send POST data request

                String charset = "UTF-8";
                URLConnection conn = url.openConnection();
                conn.setReadTimeout(5000);
                System.out.println("coonnected.: ");

                Permission p = conn.getPermission();
                System.out.println("permission: " + p.toString());
                conn.setDoOutput(true);
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
                System.out.println("output gate opened.."+conn.toString());
                OutputStream wr;
                try {
                    //conn.connect();
                    wr = conn.getOutputStream();
                    if(wr == null){
                        System.out.println("-> no stream!");
                    }
                    else {
                        wr.write(data.getBytes(Charset.forName(charset)));

                        //wr.flush();
                        wr.close();
                    }

                } catch (UnknownServiceException use){
                    System.out.println("error unknown server: "+use.getMessage());
                } catch (IOException connOI){
                    System.out.println("error io stream: "+connOI.getMessage());
                } catch (Exception connOSW){
                    System.out.println("error writing to stream: "+connOSW.getMessage());
                }
                // Get the server response

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while((line = reader.readLine()) != null)
                {
                    // Append server response in string
                    sb.append(line + "\n");
                }


                text = sb.toString();
            }
            catch(Exception ex)
            {

            }
            finally
            {
                try
                {

                    reader.close();
                }

                catch(Exception ex) {}
            }

            // Show response on activity
            content.setText( text  );

        }

    }



    }

0 个答案:

没有答案