2016-10-03 2 views
0

У меня есть 2 разных класса, первого класса Tracking.java и второго класса ReportingService.java. как передать адрес местоположения в ReportingService.java в Tracking.java?Как пройти onReceived данные между классами Android

private void doLogout(){ 
    Log.i(TAG, "loginOnClick: "); 
    //ReportingService rs = new ReportingService(); 
    //rs.sendUpdateLocation(boolean isUpdate, Location); 
    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(NetHelper.getDomainAddress(this)) 
      .addConverterFactory(ScalarsConverterFactory.create()) 
      .build(); 

    ToyotaService toyotaService = retrofit.create(ToyotaService.class); 

    // caller 
    Call<ResponseBody> caller = toyotaService.logout("0,0", 
      AppConfig.getUserName(this), 
      "null"); 
    // async task 
    caller.enqueue(new Callback<ResponseBody>() { 
     @Override 
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
      try { 
       Log.i(TAG, "onResponse: "+response.body().string()); 
      }catch (IOException e){} 

     } 

     @Override 
     public void onFailure(Call<ResponseBody> call, Throwable t) { 
      Log.e(TAG, "onFailure: ", t); 
     } 
    }); 

    AppConfig.saveLoginStatus(this, AppConfig.LOGOUT); 
    AppConfig.storeAccount(this, "", ""); 

    Intent intent = new Intent(this, Main2Activity.class); 
    startActivity(intent); 
    finish(); 
} 

Этот код адрес

Call<ResponseBody> caller = toyotaService.logout("0,0", 
      AppConfig.getUserName(this), 
      "null"); 

месте И это класс ReportingService.java расположение кода ПОЛУЧИТЬ долготы, широты и адрес местонахождения от Googlemap

private void sendUpdateLocation(boolean isUpdate, Location location) { 
    Log.i(TAG, "onLocationChanged "+location.getLongitude()); 

    Geocoder geocoder; 
    List<Address> addresses; 
    geocoder = new Geocoder(this, Locale.getDefault()); 
    String street = "Unknown"; 
    try { 
     addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
     if (addresses != null) { 
      String address = addresses.get(0).getAddressLine(0); 
      String city = addresses.get(0).getLocality(); 
      String state = addresses.get(0).getAdminArea(); 
      String country = addresses.get(0).getCountryName(); 
      String postalCode = addresses.get(0).getPostalCode(); 
      String knowName = addresses.get(0).getFeatureName(); 
      street = address + " " + city + " " + state + " " + country + " " + postalCode + " " + knowName; 
      Log.i(TAG, "street "+street); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    if (isUpdate) 
     NetHelper.report(this, AppConfig.getUserName(this), location.getLatitude(), 
       location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() { 
      @Override 
      public void preEvent() { 

      } 

      @Override 
      public void postEvent(String... result) { 
       try { 
        int nextUpdate = NetHelper.getNextUpdateSchedule(result[0]); // in second 
        Log.i(TAG, "next is in " + nextUpdate + " seconds"); 
        if (nextUpdate > 60) { 
         dismissNotification(); 
         isRunning = false; 
        } else if (!isRunning){ 
         showNotification(); 
         isRunning = true; 
        } 
        handler.postDelayed(location_updater, nextUpdate * 1000 /*millisecond*/); 
       }catch (JSONException e){ 
        Log.i(TAG, "postEvent error update"); 
        e.printStackTrace(); 
        handler.postDelayed(location_updater, getResources().getInteger(R.integer.interval) * 1000 /*millisecond*/); 
       } 
      } 
     }); 
    else 
     NetHelper.logout(this, AppConfig.getUserName(this), location.getLatitude(), 
       location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() { 
      @Override 
      public void preEvent() { 

      } 

      @Override 
      public void postEvent(String... result) { 
       Log.i(TAG, "postEvent logout "+result); 
      } 
     }); 
} 

Thanks

ответ

0

Используйте библиотеку this и следуйте приведенному в ней примеру. Для передачи всего, что угодно, в любом месте.

0

Я думаю, что просто использование интерфейса решит вашу проблему. псевдокод

ReportingException.java

добавить этот

public interface myLocationListner{ 
onRecievedLocation(String location); 
} 

private myLocationListner mylocation; 

// добавить ниже линии, где вы получите уличный адрес

mylocation.onRecievedLocation(street); 

затем реализовать myLocationListner в Tracking.java там вы go :)

0

Вы можете использовать намерение:

Намерение будет срабатывать 2-й приемник и передавать данные в этот

If BroadcastReceiver:

Intent intent = new Intent(); 
intent.setAction("com.example.2ndReceiverFilter"); 
intent.putExtra("key" ,); //put the data you want to pass on 
getApplicationContext().sendBroadcast(intent); 

Если служба:

Intent intent = new Intent();` 
intent.putExtra("key" , value); //put the data you want to pass on 
startService(ReportingService.this , Tracking.class); 

в Tracking.java, чтобы получить данные, которые вы передали: внутри onReceive, сначала введите этот код

intent.getExtras().getString("key");//if int use getInt("key") 
Смежные вопросы