2016-08-15 2 views
0

Android Studio를 처음 사용하면 대용량으로 사용할 수 있습니다. 여기 코드 : https://stackoverflow.com/a/30937657/5919360을 사용하면 원하는 정보를 URL에서 성공적으로 가져올 수 있었지만 사용 방법을 알 수는 없습니다.Android Studio에서 DownloadTask의 정보 표시 및 사용

참고 : IMEI는 사용자 등록을 확인하는 좋은 방법이 아니며 나중에 변경됩니다.

public class MainActivity extends Activity { 
    private static final String TAG = MainActivity.class.getSimpleName(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // Create instance and populates based on content view ID 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
     // store IMEI 
     String imei = tm.getDeviceId(); 
     // store phone 
     String phone = tm.getLine1Number(); 

     // Display IMEI - Testing Purposes Only 
     TextView imeiText = (TextView) findViewById(R.id.imeiDisplay); 
     imeiText.setText("IMEI:" + imei); 
     // Display phone number - Testing Purposes Only 
     TextView phoneText = (TextView) findViewById(R.id.phoneDisplay); 
     phoneText.setText("Phone:" + phone); 

     new DownloadTask().execute("http://www.url.com/mobileAPI.php?action=retrieve_user_info&IMEI="+imei); 

    } 

    private class DownloadTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      try { 
       return downloadContent(params[0]); 
      } catch (IOException e) { 
       return "Unable to retrieve data. URL may be invalid."; 
      } 
     } 

     @Override 
     protected void onPostExecute(String result) { 

      Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); 

     } 
    } 

    private String downloadContent(String myurl) throws IOException { 
     InputStream is = null; 
     int length = 500; 

     try { 
      URL url = new URL(myurl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(10000 /* milliseconds */); 
      conn.setConnectTimeout(15000 /* milliseconds */); 
      conn.setRequestMethod("GET"); 
      conn.setDoInput(true); 
      conn.connect(); 
      int response = conn.getResponseCode(); 
      Log.d(TAG, "The response is: " + response); 
      is = conn.getInputStream(); 

      // Convert the InputStream into a string 
      String contentAsString = convertInputStreamToString(is, length); 
      return contentAsString; 
     } finally { 
      if (is != null) { 
       is.close(); 
      } 
     } 
    } 

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException { 
     Reader reader = null; 
     reader = new InputStreamReader(stream, "UTF-8"); 
     char[] buffer = new char[length]; 
     reader.read(buffer); 
     return new String(buffer); 
    } 
} 

이 코드는 토스트로, XML 파일을 반환

<?xml version="1.0" encoding="ISO-8859-1"?> 
<mobile_user_info> 
<rec>45</rec> 
<IMEI>9900990099009</IMEI> 
<fname>First</fname> 
<lname>Last</lname> 
<instance>instance1</instance> 
<registered>N</registered> 
</mobile_user_info> 

내가 바라고 누군가가 각 라인을 분리하고 독립적으로 사용을위한 올바른 방향으로 날 지점 수 있습니다. 예를 들어, 등록 된 행이 N으로 되돌아 오면 '등록되지 않았습니다.'와 같은 메시지가 표시됩니다. 관리자에게 문의하십시오. '

답변

0

사실 XML 파서를 사용하여 서버의 응답을 구문 분석해야합니다. 그러나 응답이 예제처럼 항상 간단한 경우 일반 표현식을 사용하여 IMEI 필드를 추출 할 수 있습니다.

String contentAsString = ... 
Pattern pattern = Pattern.compile("<IMEI>(\d*)</IMEI>"); 
Matcher matcher = pattern.matcher(contentAsString); 
if (matcher.find()) { 
    String imei = matcher.group(1); 
} 
관련 문제