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


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


逻辑代码文件:

<span style="font-size:18px;">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);
    }
}
</span>


布局文件:

<span style="font-size:18px;"><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/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="IntentService下载图片" 
        android:onClick="click"/>
    

</RelativeLayout>
</span>


服务类:

<span style="font-size:18px;">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("网络异常请检查");
		}
		
	}

}
</span>


请求网络工具类:

<span style="font-size:18px;">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;
		
	}
}
</span>


写入到SD卡工具类:

<span style="font-size:18px;">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;
		
	}
	
}
</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值