2015-11-26 23 views

回答

1

不錯的問題作爲初學者,但爲此,你需要了解意向服務。

1.什麼是IntentService?

  • IntentService是android.app.Service類的子類。規定的 意圖服務允許處理長時間運行的任務,而不影響應用程序UI線程。這不受任何活動約束,因此,它不會因任何活動生命週期變化而受到影響。一旦 IntentService啓動,它將使用工作線程處理每個意圖 線程,並在其用完工作時自行停止。
  • 使用IntentService,只能有一個請求在任何 單個時間點處理。如果您請求執行其他任務,則新的作業將等待直到前一個任務完成。這意味着 IntentService處理該請求。

    我們將創建一個IntentService從服務器下載數據:

  • 的任務使用IntentService不能中斷

2.創建一個IntentService說明。一旦下載完成,響應將被髮送回活動。讓我們創建一個新類DownloadService.java並從android.app.IntentService中擴展它。現在讓我們重寫onHandleIntent()方法。

public class DownloadService extends IntentService { 

    public static final int STATUS_RUNNING = 0; 
    public static final int STATUS_FINISHED = 1; 
    public static final int STATUS_ERROR = 2; 

    private static final String TAG = "DownloadService"; 

    public DownloadService() { 
     super(DownloadService.class.getName()); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

     Log.d(TAG, "Service Started!"); 

     final ResultReceiver receiver = intent.getParcelableExtra("receiver"); 
     String url = intent.getStringExtra("url"); 

     Bundle bundle = new Bundle(); 

     if (!TextUtils.isEmpty(url)) { 
      /* Update UI: Download Service is Running */ 
      receiver.send(STATUS_RUNNING, Bundle.EMPTY); 

      try { 
       String[] results = downloadData(url); 

       /* Sending result back to activity */ 
       if (null != results && results.length > 0) { 
        bundle.putStringArray("result", results); 
        receiver.send(STATUS_FINISHED, bundle); 
       } 
      } catch (Exception e) { 

       /* Sending error message back to activity */ 
       bundle.putString(Intent.EXTRA_TEXT, e.toString()); 
       receiver.send(STATUS_ERROR, bundle); 
      } 
     } 
     Log.d(TAG, "Service Stopping!"); 
     this.stopSelf(); 
    } 

    private String[] downloadData(String requestUrl) throws IOException, DownloadException { 
     InputStream inputStream = null; 
     HttpURLConnection urlConnection = null; 

     /* forming th java.net.URL object */ 
     URL url = new URL(requestUrl); 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     /* optional request header */ 
     urlConnection.setRequestProperty("Content-Type", "application/json"); 

     /* optional request header */ 
     urlConnection.setRequestProperty("Accept", "application/json"); 

     /* for Get request */ 
     urlConnection.setRequestMethod("GET"); 
     int statusCode = urlConnection.getResponseCode(); 

     /* 200 represents HTTP OK */ 
     if (statusCode == 200) { 
      inputStream = new BufferedInputStream(urlConnection.getInputStream()); 
      String response = convertInputStreamToString(inputStream); 
      String[] results = parseResult(response); 
      return results; 
     } else { 
      throw new DownloadException("Failed to fetch data!!"); 
     } 
    } 

    private String convertInputStreamToString(InputStream inputStream) throws IOException { 

     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
     String result = ""; 

     while ((line = bufferedReader.readLine()) != null) { 
      result += line; 
     } 

      /* Close Stream */ 
     if (null != inputStream) { 
      inputStream.close(); 
     } 

     return result; 
    } 

    private String[] parseResult(String result) { 

     String[] blogTitles = null; 
     try { 
      JSONObject response = new JSONObject(result); 
      JSONArray posts = response.optJSONArray("posts"); 
      blogTitles = new String[posts.length()]; 

      for (int i = 0; i < posts.length(); i++) { 
       JSONObject post = posts.optJSONObject(i); 
       String title = post.optString("title"); 
       blogTitles[i] = title; 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return blogTitles; 
    } 

    public class DownloadException extends Exception { 

     public DownloadException(String message) { 
      super(message); 
     } 

     public DownloadException(String message, Throwable cause) { 
      super(message, cause); 
     } 
    } 
} 

3.How它工作延伸IntentService和重寫onHandleIntent()方法

  1. 下載服務類。在onHandleIntent()方法中,我們將執行我們的網絡請求以從服務器下載數據

  2. 在從服務器下載數據之前,請求將從捆綁中獲取。在啓動

  3. 一旦下載成功後,我們將通過ResultReceiver

  4. 響應返回給活動的任何異常或錯誤我們的活動會將此數據作爲演員,我們將傳遞錯誤響應返回給活動通過ResultReceiver。

  5. 我們已經聲明瞭自定義異常類DownloadException來處理我們所有的自定義錯誤消息。您可以在清單

    般的服務做到這一點

4.申報服務,IntentService也需要在應用程序清單中的條目。提供元素條目並聲明您使用的所有IntentServices。此外,由於我們正在執行從互聯網下載數據的操作,因此我們將請求獲得android.permission.INTERNET權限。

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.javatechig.intentserviceexample"> 

    <!-- Internet permission, as we are accessing data from server --> 
    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme"> 
     <activity 
      android:name=".MyActivity" 
      android:label="@string/app_name"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 


     <!-- Declaring Service in Manifest --> 
     <service 
      android:name=".DownloadService" 
      android:exported="false" /> 

    </application> 

</manifest> 

6.發送工作請求到IntentService

要開始下載服務下載數據,你必須創建一個明確的意圖,所有的請求參數添加到它。可以通過調用startService()方法來啓動服務。您可以啓動一個IntentService,以形成一個Activity或一個Fragment。

這裏有什麼額外的DownloadResultReceiver,是吧?請記住,我們必須將服務下載請求的結果傳遞給活動。這將通過ResultReceiver完成。

/* Starting Download Service */ 
mReceiver = new DownloadResultReceiver(new Handler()); 
mReceiver.setReceiver(this); 
Intent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class); 

/* Send optional extras to Download IntentService */ 
intent.putExtra("url", url); 
intent.putExtra("receiver", mReceiver); 
intent.putExtra("requestId", 101); 

startService(intent); 

只要按照您的要求相同和更改。 並記住***** 一旦IntentService啓動,它就會使用工作線程處理每個Intent,並在工作不成功時自行停止。

+1

感謝分享知識:) ...這是可觀的 –