2016-08-11 90 views
0

我需要發佈我的JSONArray到服務器,我試過HttpUrlConnection但我不知道如何在我的情況下使用ASyncTask。POST JSONArray到服務器使用HttpUrlConnection

在我的onLocationChanged方法中,我需要每10秒發佈一次該JSON。有誰知道如何做到這一點?

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{ 

    private final String LOG_TAG = "iTrackerTestApp"; 
    private TextView txtLatitude, txtLongitude, txtAltitude, txtVelocidade; 
    private GoogleApiClient mGoogleApiClient; 
    private HttpURLConnection urlConnection = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 

     txtLatitude = (TextView) findViewById(R.id.txtLatitude); 
     txtLongitude = (TextView) findViewById(R.id.txtLongitude); 
     txtAltitude = (TextView) findViewById(R.id.txtAltitude); 
     txtVelocidade = (TextView) findViewById(R.id.txtVelocidade); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     LocationRequest mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(1000); // Atualiza a localização a cada segundo. 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Log.i(LOG_TAG, location.toString()); 

     txtLatitude.setText("Latitude: " + Double.toString(location.getLatitude())); 
     txtLongitude.setText("Longitude: " + Double.toString(location.getLongitude())); 
     if(location.hasAltitude()) 
      txtAltitude.setText("Altitude: " + Double.toString(location.getAltitude())); 
     if(location.hasSpeed()) 
      txtVelocidade.setText("Velocidade: " + Float.toString(location.getSpeed())); 

     final JSONArray array = new JSONArray(); 
     JSONObject jsonObject = new JSONObject(); 

     try { 
      jsonObject.put("Latitude", txtLatitude.getText()); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     try { 
      jsonObject.put("Longitude", txtLongitude.getText()); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     array.put(jsonObject); 

     // I NEED TO SEND THIS JSON TO SERVER EVERY 10 SECONDS 
    } 

    @Override 
    protected void onStart(){ 
     super.onStart(); 
     mGoogleApiClient.connect(); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
    } 

    @Override 
    protected void onStop(){ 
     mGoogleApiClient.disconnect(); 
     super.onStop(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     Log.i(LOG_TAG, "Conexão com o GoogleApiClient suspensa!"); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Log.i(LOG_TAG, "Conexão com o GoogleApiClient falhou!"); 
    } 
} 

回答

2

坦率地說,ASyncTask是老式和很多鍋爐板編碼。您需要切換到Retrofit,這是用作HTTP客戶端的最佳庫。給它一個鏡頭,你永遠不會回頭。這是你如何在改造中做到這一點。

這是你如何在改造

public static final String BASE_URL = "http://api.myservice.com/"; 
Retrofit retrofit = new Retrofit.Builder() 
    .baseUrl(BASE_URL) 
    .addConverterFactory(GsonConverterFactory.create()) 
    .build(); 

然後定義你的終點到您的JSON發送到服務器的REST API的身體,你做兩件事情。首先把它定義爲如下

public interface MyApiEndpointInterface 
{ 
    @POST("users/new") 
    Call<User> createUser(@Body User user); 
} 

而在你的活動中,你使用它,如下

User user = new User(123, "John Doe"); 
Call<User> call = apiService.createuser(user); 
call.enqueue(new Callback<User>() { 
    @Override 
    public void onResponse(Call<User> call, Response<User> response) { 
    } 

    @Override 
    public void onFailure(Call<User> call, Throwable t) { 
    } 

你所有的AsyncTask活動在上面的調用處理。就這麼簡單。

以上調用將以下JSON發送到服務器

{"name":"John Doe","id":123} 
+0

我不明白的用戶類別。 –

+0

用戶類是一個簡單的POJO。 –

+0

http://www.jsonschema2pojo.org使用它爲你的json創建一個POJO –