我可以在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. 安卓系统毫秒转换
感谢分享知识:) ...这是可观的 –