现在的位置: 首页 > 综合 > 正文

利用后台服务下载网络数据

2017年11月18日 ⁄ 综合 ⁄ 共 2922字 ⁄ 字号 评论关闭

/**

 * service运行在主线程里所以不能使用HTTP协议访问网络

 * 

 * try catch的实例尽量在该块外面定义

 */

public class MyService extends Service {

 

 

 

public MyService() {

// TODO Auto-generated constructor stub

}

 

@Override

public void onCreate() {

// TODO Auto-generated method stub

super.onCreate();

}

 

 

 

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

//获得图片地址

final String url=intent.getStringExtra("image_path");

final Handler handler=new Handler(){

 

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

if(msg.what==111)

{

Toast.makeText(MyService.this,"下载完成", Toast.LENGTH_LONG).show();

stopSelf();//startService()启动后,关闭service

}

}

};//注意分号

//启动线程访问网络

new Thread(new Runnable(){

 

@Override

public void run() {

//获得获取网络资源的Http客户端

HttpClient httpClient=new DefaultHttpClient(); 

//请求方式

HttpPost httpPost=new HttpPost(url);

HttpResponse httpResponse=null;

//网络资源的字节数组

byte[] data=null;

//文件存储路径

File file=new File(Environment.getExternalStorageDirectory(),"图片后台下载.jpg");

FileOutputStream fileOutputStream=null;

try {

//执行请求获得响应

httpResponse=httpClient.execute(httpPost);

//判断响应是否成功

if(httpResponse.getStatusLine().getStatusCode()==200)

{

//获得内容的字节数组

data=EntityUtils.toByteArray(httpResponse.getEntity());

//判断SD卡是否可用

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

{

fileOutputStream=new FileOutputStream(file);

fileOutputStream.write(data, 0,data.length);

//完成下载发送消息

Message message=Message.obtain();

message.what=111;

handler.sendMessage(message);//向主线程发送消息

}

}

catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(fileOutputStream!=null)

{

try {

fileOutputStream.close();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//关闭该进程

if(httpClient!=null)

{

httpClient.getConnectionManager().shutdown();

}

}

}}).start();

return super.onStartCommand(intent, flags, startId);

}

 

 

@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}

@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

}

 

}

public class MainActivity extends Activity {

 

private String url="http://p16.qhimg.com/bdr/__85/d/_open360/fengjing0321/9.jpg";

private Button btnDownload=null;

private ImageView image=null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btnDownload=(Button)this.findViewById(R.id.button1);

image=(ImageView)this.findViewById(R.id.imageView1);

btnDownload.setOnClickListener(new OnClickListener(){

 

@Override

public void onClick(View v) {

Intent intent=new Intent(MainActivity.this,MyService.class);

intent.putExtra("image_path",url);

startService(intent);

}

});

}

 

@Override

public 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;

}

 

}

【上篇】
【下篇】

抱歉!评论已关闭.