安卓Service组件使用系列3:使用IntentService下载网络图片

来源:互联网 发布:linux 查看文件夹数量 编辑:程序博客网 时间:2024/04/29 20:51
使用IntentService的特点:
1.不需要开启线程
2.不需要关闭服务,自己会关闭
3.使用单线程下载数据       
(不需要完成线程的编写,直接访问网络就可以获取图片)

因为以上两点都在它的类源码中封装好了。

在面我们看一下它的使用方法。

整体思路:在xml文件中放置一个Button控件,在这个Button点击事件中开启Service。定义一个DownLoadService类,继承IntentService类,在这个类中重写onHandleIntent方法,在这个方法中下载网络图片。注意在清单文件AndroidManifest.xml中,声明访问网络的授权和读取sdcard卡的授权。

activity_main.xml文件:

<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" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="146dp"        android:text="使用IntentService下载网络图片" /></RelativeLayout>
MainActivity.java文件:

package com.example.android_intentservice;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button=(Button)findViewById(R.id.button1);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubIntent intent=new Intent(MainActivity.this,DownLoadService.class);startService(intent);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
DownLoadService.java文件:

package com.example.android_intentservice;import java.io.File;import java.io.FileOutputStream;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.protocol.DefaultedHttpContext;import org.apache.http.util.EntityUtils;import android.app.IntentService;import android.content.Intent;import android.os.Environment;import android.widget.Toast;//使用IntentService的特点://1.不需要开启线程//2.不需要关闭服务,自己会关闭//3.使用单线程下载数据       //(不需要完成线程的编写,直接访问网络就可以获取图片)//因为以上两点都在它的类源码中封装好了public class DownLoadService extends IntentService {private final String  IMAGE_PATH="https://www.baidu.com/img/bd_logo1.png";//默认这里要传一个参数public DownLoadService() {super("DownLoadService");// TODO Auto-generated constructor stub}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}@Overrideprotected void onHandleIntent(Intent intent) {// TODO Auto-generated method stub        HttpClient httpClient=new DefaultHttpClient();        HttpPost post=new HttpPost(IMAGE_PATH);        HttpResponse response=null;//      得到sdcard的存储目录        File file=Environment.getExternalStorageDirectory();        FileOutputStream outputStream=null;        try {response=httpClient.execute(post);if(response.getStatusLine().getStatusCode()==200){byte[] result=EntityUtils.toByteArray(response.getEntity());if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){File new_file=new File(file,"bd_logo1.png");outputStream=new FileOutputStream(new_file);outputStream.write(result,0,result.length);Toast.makeText(getApplicationContext(), "下载文件完毕!!", 1).show();}}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{try {if(outputStream!=null){outputStream.close();}} catch (Exception e2) {// TODO: handle exception}httpClient.getConnectionManager().shutdown();}}}




1 0
原创粉丝点击