今天讲下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 {
@Override
protected 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("");
}
@Override
public void onCreate() {
super.onCreate();
Log.i("main", "-----onCreate----->>");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("main", "-----onStartCommand----->>");
return super.onStartCommand(intent, flags, startId);
}
// 执行耗时操作,该方法会默认开启工作线程
@Override
protected 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", "图片保存成功");
}
}
}
}
@Override
public 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();
// 返回true
return 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"/>