安卓:IntentService实现网络下载图片并写入到SD卡


清单文件中注册服务,添加权限


逻辑代码文件:

package com.example.day22_intentservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

	private static final String path ="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
    }
    public void click(View v)
    {
    	Intent intent=new Intent(MainActivity.this,MyService.class);
    	intent.putExtra("path",path);
    	startService(intent);
    }
}


布局文件:



    


服务类:

package com.example.day22_intentservice;

import android.app.IntentService;
import android.content.Intent;

/*
 * 如果一个线程能满足操作   就用IntentService
 * 如果一个线程不能满足操作   就用service
 * 
 * 继承IntentService  耗时操作  在onHandleIntent 执行  
 * 执行完毕之后  会执行ondestroy()
 */
public class MyService extends IntentService{

	public MyService(String name) {
		super(name);
	}
	public MyService() {
		super("");
	}
	//底层封装了一个工作线程
	@Override
	protected void onHandleIntent(Intent intent) {
		String path = intent.getStringExtra("path");
		if(HttpData.isConn(MyService.this))
		{
			byte b[]=HttpData.getData(path);
			if(b!=null&&b.length>0)
			{
				if(WriteFile.isConn())
				{
					boolean r=WriteFile.write(b, path);
					if(r)
					{
						System.out.println("写入成功");
						stopSelf();//关闭服务
					}
					else
					{
						System.out.println("写入失败");
					}
				}
				else
				{
					System.out.println("SD卡不可用");
				}
			}
			else
			{
				System.out.println("图片下载失败");
			}
		}
		else
		{
			System.out.println("网络异常请检查");
		}
		
	}

}


请求网络工具类:

package com.example.day22_intentservice;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpData {

	public static boolean isConn(Context context)
	{
		ConnectivityManager m=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = m.getActiveNetworkInfo();
		if(info!=null)
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
	public static byte[] getData(String path)
	{
		ByteArrayOutputStream bo=new ByteArrayOutputStream();
		try 
		{
			URL url=new URL(path);
			HttpURLConnection con=(HttpURLConnection) url.openConnection();
			con.setConnectTimeout(5000);
			con.setDoInput(true);
			con.connect();
			if(con.getResponseCode()==200)
			{
				InputStream in = con.getInputStream();
				int count=0;
				byte b[]=new byte[1024];
				while((count=in.read(b))!=-1)
				{
					bo.write(b, 0, count);
					bo.flush();
				}
			}
			return bo.toByteArray();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
		
	}
}


写入到SD卡工具类:

package com.example.day22_intentservice;

import java.io.File;
import java.io.FileOutputStream;

import android.os.Environment;

public class WriteFile {

	public static boolean isConn()
	{
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			return true;			
		}
		return false;
	}
	public static boolean write(byte b[],String path)
	{
		boolean flag=false;
		String name=path.substring(path.lastIndexOf("/")+1);
		File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name);
		try 
		{
			FileOutputStream fo=new FileOutputStream(file);
			fo.write(b);
			flag=true;
			fo.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return flag;
		
	}
	
}


你可能感兴趣的:(安卓)