Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用异步任务android向服务器发送定期位置更新_Java_Android - Fatal编程技术网

Java 使用异步任务android向服务器发送定期位置更新

Java 使用异步任务android向服务器发送定期位置更新,java,android,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.BufferedReade

我正在尝试开发一个应用程序,通过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  );

        }

    }



    }
package com.example.vikram.locationinterval;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.UnsupportedEncodingException;
导入java.net.URL;
导入java.net.URLConnection;
导入java.net.urlcoder;
导入java.net.UnknownServiceException;
导入java.nio.charset.charset;
导入java.security.Permission;
导入android.app.Activity;
导入android.content.Context;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展活动实现LocationListener{
受保护的LocationManager LocationManager;
TextView txtLat,内容;
受保护静态int intervalInMillis=500;
@凌驾
创建时受保护的void(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\u服务);
locationManager.RequestLocationUpdate(locationManager.GPS_提供程序,intervalInMillis,0.5f,本);
}
@凌驾
已更改位置上的公共无效(位置){
long now=System.currentTimeMillis();
txtLat=(TextView)findViewById(R.id.textview1);
txtLat.setText(“纬度:“+location.getLatitude()+”,经度:“+location.getLatitude()+”\n now=“+now”);
试一试{
System.out.println(“\n测试2-发送Http POST请求”);
新的MyAsyncTask(String.valueOf(location.getLatitude())、String.valueOf(location.getLatitude()).execute();
}
捕获(例外情况除外)
{
//System.out.println(例如getCause());
}
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
Log.d(“纬度”、“禁用”);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
Log.d(“纬度”、“启用”);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
Log.d(“纬度”、“状态”);
}
私有类MyAsyncTask扩展了AsyncTask{
保护字符串纬度、经度;
受保护的MyAsyncTask(字符串lat、字符串lon){
这个纬度=纬度;
这个经度=lon;
}
@凌驾
受保护的双doInBackground(字符串…参数){
//TODO自动生成的方法存根
试一试{
postData(this.latitude,this.longitude);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(双重结果){
Toast.makeText(getApplicationContext(),“已发送命令”,Toast.LENGTH_LONG.show();
}
public void postData(字符串Lat、字符串Lon)引发UnsupportedEncodingException{
//为发送到服务器的值创建数据变量
字符串数据=URLEncoder.encode(“纬度”,“UTF-8”)
+“=”+URLEncoder.encode(Lat,“UTF-8”);
数据+=”&“+URLCoder.encode(“经度”,“UTF-8”)+”=”
+编码(Lon,“UTF-8”);
系统输出打印项次(数据);
字符串文本=”;
BufferedReader reader=null;
//发送数据
尝试
{
//已定义用于发送数据的URL
URL=新URL(“http://10.0.2.2:8080/GetSomeRest/webresources/service");
//发送POST数据请求
字符串charset=“UTF-8”;
URLConnection conn=url.openConnection();
连接设置读取超时(5000);
System.out.println(“连接:”);
权限p=conn.getPermission();
System.out.println(“权限:+p.toString());
连接设置输出(真);
conn.setRequestProperty(“接受字符集”,字符集);
conn.setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=“+charset”);
System.out.println(“输出门打开..”+conn.toString());
输出流wr;
试一试{
//连接();
wr=连接getOutputStream();
如果(wr==null){
System.out.println(“->无流!”);
}
否则{
write(data.getBytes(Charset.forName(Charset));
//wr.flush();
wr.close();
}
}捕获(未知服务异常使用){
System.out.println(“错误未知服务器:+use.getMessage());
}捕获(IoConnoi){
System.out.println(“错误io流:+connOI.getMessage());
}catch(异常connOSW){
System.out.println(“写入流时出错:+connOSW.getMessage());
}
//获取服务器响应
reader=新的BufferedReader(新的InputStreamReader(conn.getInputStream());
StringBuilder sb=新StringBuil