意图服务是异步进行的  执行完操作后就会自己消毁(onDestroy方法)

本例为点击按钮下载三张图片相当于连续执行三次意图服务中的onStartcommand方法

 import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout; public class MainActivity extends Activity { private ImageView img1View,img2View,img3View;
private RelativeLayout mainLayout; private ImgReceiver imgReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mainLayout=(RelativeLayout) findViewById(R.id.mainLayoutId); img1View=(ImageView) findViewById(R.id.img1Id);
img2View=(ImageView) findViewById(R.id.img2Id);
img3View=(ImageView) findViewById(R.id.img3Id); img1View.setTag(Config.URL1);
img2View.setTag(Config.URL2);
img3View.setTag(Config.URL3); imgReceiver=new ImgReceiver();
registerReceiver(imgReceiver,
new IntentFilter(Config.ACTION_DOWNLOAD_COMPLETED)); } public void startDownload(View view){
Intent intent=new Intent(getApplicationContext(),DownloadService.class);
intent.putExtra("path", Config.URL1);
startService(intent); //涓嬭浇绗竴涓浘鐗�
intent.putExtra("path", Config.URL2);
startService(intent); //涓嬭浇绗簩涓浘鐗�
intent.putExtra("path", Config.URL3);
startService(intent); //涓嬭浇绗笁涓浘鐗�
} @Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(imgReceiver); //鍙栨秷娉ㄥ唽骞挎挱鎺ユ敹鍣�
} class ImgReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO 鎺ユ敹鍥剧墖涓嬭浇瀹屾垚鐨勫箍鎾�
String url=intent.getStringExtra(Config.EXTRA_URL);
Bitmap bitmap=intent.getParcelableExtra(Config.EXTRA_BITMAP); //鏍规嵁Url浣滀负鐨勫浘鐗囨帶浠剁殑鏍囩鏌ユ壘鍥剧墖鎺т欢
ImageView imgView=(ImageView) mainLayout.findViewWithTag(url);
imgView.setImageBitmap(bitmap);
}
} }

MainActivity.java

 import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log; /**
* IntentService鏄甫鏈夊瓙绾跨▼鐨勬湇鍔$粍浠讹紝鍏跺唴閮ㄤ娇鐢ㄤ簡鍗曠嚎绋嬫睜妯″紡锛� * 褰撴墍鏈夌殑浠诲姟鎵ц瀹屾垚鍚庯紝浼氳嚜鍔ㄥ叧闂湰鏈嶅姟
* 鍏剁敓鍛藉懆鏈熸柟娉曪細
* onCreate()
* onStartCommand()
* onHandleIntent() 鍦ㄥ瓙绾跨▼涓墽琛岀殑鏂规硶
* onDestroy()
*
* @author apple
*
*/
public class DownloadService extends IntentService {
public DownloadService(){
super(null);//鍙傛暟锛氭槸璁剧疆瀛愮嚎绋嬬殑鍚嶇О
} @Override
public void onCreate() {
super.onCreate();
Log.i("debug", "--onCreate---");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("debug", "--onStartCommand---");
return super.onStartCommand(intent, flags, startId);
} @Override
protected void onHandleIntent(Intent intent) {
// TODO 鍦ㄥ瓙绾跨▼涓墽琛岀殑鏂规硶
Log.i("debug", "--onHandleIntent---");
//鑾峰彇涓嬭浇鍥剧墖鐨勫湴鍧�
String path=intent.getStringExtra("path");
try{
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
InputStream is=conn.getInputStream();
byte[] buffer=new byte[10*1024];//姣忔璇诲彇瀛楄妭鐨勬渶澶ф暟
int len=-1; ByteArrayOutputStream baos=new ByteArrayOutputStream();
if(conn.getResponseCode()==200){
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
} byte[] bytes=baos.toByteArray();
//灏嗕笅杞藉畬鎴愮殑瀛楄妭鏁扮粍杞垚鍥剧墖瀵硅薄
Bitmap bitmap=BitmapFactory.decodeByteArray(bytes, 0, bytes.length); //灏嗗浘鐗囧璞″彂閫佺粰Activity杩涜鏄剧ず
Intent bitmapIntent=new Intent(Config.ACTION_DOWNLOAD_COMPLETED);
bitmapIntent.putExtra(Config.EXTRA_BITMAP,bitmap);
bitmapIntent.putExtra(Config.EXTRA_URL, path); sendBroadcast(bitmapIntent); Thread.sleep(2000);//浠呮祴璇曟椂浣跨敤
} }catch(Exception e){
e.printStackTrace();
} } @Override
public void onDestroy() {
super.onDestroy();
Log.i("debug", "--onDestroy---");
} }

DownLoadService.java

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/mainLayoutId"> <Button
android:id="@+id/btnId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startDownload"
android:text="开始下载" /> <ImageView
android:id="@+id/img1Id"
android:layout_width="100dp"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_margin="5dp"
android:layout_below="@id/btnId"/> <ImageView
android:id="@+id/img2Id"
android:layout_width="100dp"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_margin="5dp"
android:layout_below="@id/btnId"
android:layout_toRightOf="@id/img1Id"/> <ImageView
android:id="@+id/img3Id"
android:layout_width="100dp"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_margin="5dp"
android:layout_below="@id/img1Id"/> </RelativeLayout>

activity_main.xml

至于服务的类都需要注册  这里就不写了

IntentService----意图服务的更多相关文章

  1. 服务 IntentService 前台服务 定时后台服务

    Activity public class MainActivity extends ListActivity {     private int intentNumber = 0;     @Ove ...

  2. IntentService用于服务中开启子线程的自动关闭

    package com.pingyijinren.test; import android.app.IntentService; import android.content.Intent; impo ...

  3. [Android] Service服务详解以及如何使service服务不被杀死

    排版上的细节有些不好看,主要是我用的MarkDown编辑器预览和这里的不一样,在那个上面的样式很舒服.这里要改的地方太多就不想改了,将就看吧.下次写的时候注意.还有看到错误给我提啊. 本文链接:htt ...

  4. Android 服务入门

    前言:硬着头皮把数据库SQLite看完了,接下来就是android服务了,因为自己本身就是菜鸟,所以呢,也只是做做笔记,技术上的东西就别指望我了. 1.什么是服务呢?举个例子,百度地图,美团外卖,OF ...

  5. Android 服务类Service 的详细学习

    http://blog.csdn.net/vipzjyno1/article/details/26004831 Android服务类Service学习四大组建   目录(?)[+] 什么是服务 服务有 ...

  6. Android(java)学习笔记266:Android线程形态之 IntentService

    1. IntentService原理 IntentService是一种特殊的Service,既然是Service,使用的时候记得在AndroidManifest清单文件中注册. 并且它是一个抽象类,因 ...

  7. Android 服务类Service 的具体学习

    上一篇说到了通知栏Notification,提起通知栏,不得让人想到Service以及BroadcastReceive,作为android的4大组建的2个重要成员,我们没少和它们打交道.它们能够在无形 ...

  8. Android HandlerThread和IntentService

    HandlerThreadHandlerThread继承了Thread,它是一种可以使用Handler的Thread,它实现也很简单,就是在run中通过Looper.prepare()来创建消息队列, ...

  9. Android四大组件-服务

    Android服务 android 的服务有点类似windows的服务,没有界面,在后台长时间运行,如果我们这种需求的话我们就可以使用服务来实现. 服务的典型应用场景: 播放音乐,下载等,如果要在一个 ...

随机推荐

  1. BCGcontrolBar(一) MFC界面库简介

    原帖地址:http://blog.csdn.net/zw514159799/article/details/9148385 英文原文:http://www.bcgsoft.com/bcgcontrol ...

  2. php变量详细讲解

    变量是用于存储信息的"容器". 定义一个变量的语法: $变量名 = 值; 使用变量的例子: <?php $x=5; $y=6; $z=$x+$y; echo $z; ?> ...

  3. python2 与python3中最大的区别(编码问题bytes&str

    1,在python2.x 中是不区分bytes和str类型的,在python3中bytes和str中是区分开的,str的所有操作bytes都支持 python2 中 >>> s = ...

  4. 提高 web 应用性能之 CSS 性能调优

    简介 Web 开发中经常会遇到性能的问题,尤其是 Web 2.0 的应用.CSS 代码是控制页面显示样式与效果的最直接“工具”,但是在性能调优时他们通常被 Web 开发工程师所忽略,而事实上不规范的 ...

  5. PL/SQL 的一些用法

    变量的声明,赋值,打印(declare是pl/sql里面的用法 variable是sql*plus里面的用法,variable相当于一个sql*plus环境的全局变量,declare里定义的是pl/s ...

  6. 使用Larave5.6l提交POST请求出现The page has expired due to inactivity错误

    使用Larave5.6l提交POST请求出现The page has expired due to inactivity错误 一般是由于没有添加 csrf造成的 在表单下面的 第一个行 添加如下代码即 ...

  7. volatile解析

    转载:http://www.importnew.com/17394.html 一.volatile简介: 在多线程并发编程中synchronized和Volatile都扮演着重要的角色,Volatil ...

  8. jmap Exception in thread "main" java.io.IOException: 拒绝访问。

    环境: 现有一个独立运行的系统S(有独立的jre,但是没jdk),现想通过jmap导出其内存堆栈信息.于是另外安装一个jdk.可是jdk的版本跟S系统的jre不能对应上.出了很多错误. 总是报错: C ...

  9. Mysql数据库查询数据文件大小

    参考网站:https://zhidao.baidu.com/question/201227796936321525.html 用SQL命令查看Mysql数据库大小 要想知道每个数据库的大小的话,步骤如 ...

  10. REST 服务器调试 RESTDebugger.exe 和浏览器测试

    开发一个简单的rest服务器, 增加了一些函数,比如返回系统当前时间 如何验证是否正确呢,不需要自己编写客户端调用程序了, 可以直接使用RESTDebugger.exe D:\Program File ...