使用IntentService实现图片的下载

来源:互联网 发布:淘宝直通车首次充值 编辑:程序博客网 时间:2024/05/17 06:08

今天讲下IntentService,我们创建一个IntentService的子类并重写其对应方法,在其onHandleIntent方法中

我们可以直接在其中执行耗时操作,而且耗时操作执行完毕后,可以自动销毁该Service。

因为基本的实现和之前的两篇图片的下载都是比较类似的,我们直接看代码吧。

MainActivity:

package com.example.text09;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;/** * IntentService:如果需要后台的网络的支持下载数据,可以通过定义一个继承自IntentService的子类实现 * 该子类会默认开启一个工作线程,处理服务要做的任务,而且工作线程完成任务后会自动停止服务 *  * @author Administrator */public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void download(View view){Intent intent = new Intent(this, MyService.class);intent.putExtra("path", "https://www.baidu.com/img/bd_logo1.png");startService(intent);}}
然后是创建一个类继承IntentService并重写其对应方法:

package com.example.text09;import com.example.http.ExternalStorageUtils;import com.example.http.HttpUtils;import android.R.integer;import android.app.IntentService;import android.content.Intent;import android.util.Log;public class MyService extends IntentService {public MyService(String name) {super(name);}public MyService() {super("");}@Overridepublic void onCreate() {super.onCreate();Log.i("main", "-----onCreate----->>");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i("main", "-----onStartCommand----->>");return super.onStartCommand(intent, flags, startId);}// 执行耗时操作,该方法会默认开启工作线程@Overrideprotected void onHandleIntent(Intent arg0) {Log.i("main", "-----onHandleIntent----->>");// 获取下载路径String path = arg0.getStringExtra("path");// 得到文件名String fileName = path.substring(path.lastIndexOf("/") + 1);// 判断网络连接状态if (HttpUtils.isNetWorkConn(MyService.this)) {// 得到图片信息的byte数组byte[] data = HttpUtils.getByteArray(path);// 如果数组中有内容if (data != null && data.length != 0) {boolean flag = ExternalStorageUtils.writeExternalStorageRoot(fileName, data, MyService.this);if (flag) {Log.i("main", "图片保存成功");}}}}@Overridepublic void onDestroy() {Log.i("main", "-----onDestroy----->>");super.onDestroy();}}
接下来是HttpUtils工具类:

package com.example.http;import java.io.IOException;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.content.Context;import android.content.Entity;import android.net.ConnectivityManager;import android.net.NetworkInfo;public class HttpUtils {// 判断网络连接状态的方法public static boolean isNetWorkConn(Context context) {boolean flag = false;ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo info = manager.getActiveNetworkInfo();if (info != null) {return info.isConnected();}return flag;}// 把网址信息解析到字节数组中public static byte[] getByteArray(String path) {HttpClient client = new DefaultHttpClient();HttpGet get = new HttpGet(path);try {HttpResponse res = client.execute(get);if (res.getStatusLine().getStatusCode() == 200) {return EntityUtils.toByteArray(res.getEntity());}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}}
然后是读写sdcard的工具类:

package com.example.http;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import android.util.Log;public class ExternalStorageUtils {// 判断sdCard是否可用public static boolean isSdcardUseful() {if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {return true;}return false;}// 存储内容public static boolean writeExternalStorageRoot(String name, byte[] data,Context context) {if (isSdcardUseful()) {// 获取sdCard的根目录File sdFile = Environment.getExternalStorageDirectory();// 创建文件的抽象路径File file = new File(sdFile, name);// 向文件中写数据try {FileOutputStream fos = new FileOutputStream(file);fos.write(data, 0, data.length);fos.flush();fos.close();// 返回truereturn true;} catch (Exception e) {e.printStackTrace();}} else {Log.i("main", "sdCard不可用");}return false;}// 读取外部存储中根目录的文件public static byte[] readExternalStorageRoot(String fileName) {ByteArrayOutputStream baos = new ByteArrayOutputStream();if (isSdcardUseful()) {File sdFile = Environment.getExternalStorageDirectory();File file = new File(sdFile, fileName);if (file.exists()) {// 读取文件try {FileInputStream fis = new FileInputStream(file);byte[] buffer = new byte[1024];int len = 0;while ((len = fis.read(buffer)) != -1) {baos.write(buffer, 0, len);baos.flush();}fis.close();return baos.toByteArray();} catch (Exception e) {e.printStackTrace();}} else {Log.i("main", "文件不存在");}}return null;}// 直接获取Bitmap的形式返回public static Bitmap readExternalStorageRootToBitmap(String fileName) {Bitmap bitmap = null;if (isSdcardUseful()) {File file = new File(Environment.getExternalStorageDirectory(),fileName);bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());}return bitmap;}}
最后是在清单文件中的配置:

<service android:name="com.example.text09.MyService"></service>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.INTERNET"/>



1 0