我可以在android中創建一個後臺服務,可以在某些特定時間完成工作後進入睡眠狀態嗎? 如果您對此有任何意見,請指導。安卓系統中的Sleepable後臺服務
回答
不錯的問題作爲初學者,但爲此,你需要了解意向服務。
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()方法
下載服務類。在onHandleIntent()方法中,我們將執行我們的網絡請求以從服務器下載數據
在從服務器下載數據之前,請求將從捆綁中獲取。在啓動
一旦下載成功後,我們將通過ResultReceiver
響應返回給活動的任何異常或錯誤我們的活動會將此數據作爲演員,我們將傳遞錯誤響應返回給活動通過ResultReceiver。
我們已經聲明瞭自定義異常類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. 安卓系統的websocket服務器,java
- 2. 安卓:後臺服務不會停止
- 3. 安卓後臺服務中的位置列表
- 4. 安卓後臺服務在一段時間後停止
- 5. 安卓服務
- 6. 安卓服務如何在系統停止時作出響應
- 7. 安卓系統服務亭模式/屏幕鎖定
- 8. 安卓系統 - 遠程服務 - 無法顯示對話框
- 9. 安卓上的kivy,後臺服務通知從未消失
- 10. Google Checkout安卓系統
- 11. 安卓系統變量
- 12. 安卓系統中的HTTP POST問題
- 13. 安卓:與系統中的關鍵
- 14. 安卓相機在後臺
- 15. 安卓服務中的多個任務
- 16. Facebook的SDK在Android的安卓系統
- 17. 安卓系統的博客webservice - localhost glassfish
- 18. 三星S2,MacOSX上的安卓系統
- 19. 安卓系統上的測試屏幕
- 20. 安卓系統上的密碼提示
- 21. 安卓系統上的Python 3.3.2+
- 22. 遇到安卓系統的問題findViewById
- 23. 準系統Linux服務器安裝
- 24. 安卓系統 - 無法理解代碼
- 25. 敵人產卵系統安卓遊戲
- 26. 安卓:平無/系統/斌/平
- 27. 安卓系統,音頻過濾器
- 28. 睡在安卓系統不工作
- 29. 安卓系統,可檢查菜單項
- 30. 安卓系統毫秒轉換
感謝分享知識:) ...這是可觀的 –