2014-10-29 4 views
0

요구 사항 : 백그라운드 서비스가 있으며 해당 서비스에서 JSON 데이터를 가져 오기 위해 REST 호출을 수행하고 있습니다. JSON 데이터를 UI로 보내고 내용을 업데이트하고 싶습니다.서비스에서 JSON 데이터를 Android에서 UI로 전송

하나의 방법, 즉 JSON 문자열 전체를 SharedPreferences에 저장하고 UI에서 검색 할 수 있지만 효율적이라고 생각하지 않습니다.

아무 생각 없나요? 요소를 업데이트하기 위해 UI에 Handler를 추가했지만 익숙하지 않았습니다.

샘플 REST 호출 코드 : 그런

DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(DATA_URL); 

httpPost.setHeader("Content-Type", "application/json"); 

//passes the results to a string builder/entity 
StringEntity se = null; 
try { 
    se = new StringEntity(RequestJSON.toString()); 
} catch (UnsupportedEncodingException e) { 
    e.printStackTrace(); 
} 

//sets the post request as the resulting string 
httpPost.setEntity(se); 

//Handles what is returned from the page 
ResponseHandler responseHandler = new BasicResponseHandler(); 

try { 
    HttpResponse response = (HttpResponse) httpClient.execute(httpPost, responseHandler); 

    // response will have JSON data that I need to update in UI 

    //Show notification 
    showNotification("Update Complete"); 



} catch (UnsupportedEncodingException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} finally { 
    // httpClient = null; 
} 
+1

먼저 코드를 게시하시기 바랍니다! –

+0

REST 호출 코드가 추가되었습니다. –

+0

인 텐트에 대해 알아야합니다. http://developer.android.com/guide/components/intents-filters.html JSON 문자열 또는 매핑 된 객체와 같은 데이터를 첨부 할 수 있습니다. 'Activity'는 그것을 사용할 수 있습니다. 또한 활동을 서비스에 바인딩하고 앱이 열려있을 때 상호 작용할 수 있습니다. – Blacklight

답변

1

이 서비스를 한 번 준비가 될하기 위해 메신저를 전달합니다

Message msg = Message.obtain(); 

Bundle data = new Bundle(); 
data.putString("Mkey", 
     Smsg); 
msg.setData(data); 


try { 
    // Send the Message back to the client Activity. 
    messenger.send(msg); 
} catch (RemoteException e) { 
    e.printStackTrace(); 
} 
+0

이전에 Message 구현을 보았습니다. JSON 객체를 메시지로 추가 할 수 있습니까? 글쎄, 그렇지 않다면 우리는 항상 전체 JSON을 문자열로 만들고 올바르게 보낼 수 있습니까? –

+1

예 JSON 문자열을 보낼 수 있습니다 또는 개체를 문자열로 변환 할 수있는 Gson 라이브러리를 사용할 수도 있고 주 스레드에서 개체를 다시 만들 수 있습니다. – H4SN

+0

기본적으로 나는 메신저를 추가해야합니다.REST 호출이 끝나고 UI에서 handleMessage를 수신하고 내 updateUI 메소드를 호출하면 send (msg);가 실행됩니다. 나는 그것을 올바르게 얻었습니까? –

0

뭔가가 당신을 위해 적합 할 수있다. TL; DR : 활동을 업데이트하는 서비스에서 수신기를 만듭니다.

private static BlaBlaService _instance; 

public static BlaBlaService getInstance() { 
    return _instance; 
} 

가에서 onCreate 함수에 _instance 필드를 채 웁니다 :

서비스에서

, 정적 기능과 정적 필드하게 지내는 호출되면

public void onCreate() { 
     super.onCreate(); 
     _instance = this; 
     ... 
} 

public void addRESTCompleteListener(RESTCompleteListener l) {...} 

이 완료 호출입니다 :

listener.RESTCompleted(JSON.whatever) 

이제 액티비티가 시작되면 서비스에 리스너를 추가하기 만하면됩니다.

BlaBlaService.getInstance().addRESTCompleteListener(listener) 

필요한 경우 모든 포인터를 폐기해야합니다.

희망이 도움이 :) UI 활동

Handler myHandler = new Handler() { 



      @Override 
      public void handleMessage(Message msg) { 

       Bundle Recevied = msg.getData(); 
       String resp = Recevied.getString("Mkey"); 

      } 
    }; 

    messenger = new Messenger(myHandler); 


} 

+0

나는 원하는 기간을 기준으로 REST 호출을 계속 호출하는 서비스 내에 타이머 코드를 가지고 있습니다. UI를 업데이트합니다. '개인 무효 performRepeatedTask() { timer.scheduleAtFixedRate (새의 TimerTask() { 공공 무효 실행() { mLocationClient.connect(); } }, 0, UPDATE_INTERVAL); }' –