利用后台服务下载网络数据
2014-09-27 18:57
267 查看
/**
* 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;
}
}
* 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;
}
}
相关文章推荐
- 利用Handler实现网络数据下载Json并转换成实体类的封装
- 在服务中、一般程序中利用 Inet 相关函数下载数据
- linux 后台把命令挂起来... + 命令下载网络数据
- 使用matlab工具研究神经网络的简单过程(网络和数据下载)
- 用 MapPoint Web Service 客户数据服务下载方法进行编程[转]
- 无NAT功能三层交换网络中利用远程与路由访问服务实现外网连接
- 利用IPSec实现网络安全之三完结篇(身份验证和加密数据)
- 如果利用XMLHTTP.SEND提交并利用ASP在后台接收所提交数据
- 利用反射原理和IExtenderProvider来实现WebControl与后台类的自动数据交换
- 利用entrez提供的web服务快速下载大批量序列信息
- 如何利用网络附加存储设备(NAS)构建数据备份(本地及远程数据备份)、数据容灾解决方案
- 一切尽在自动中(二),sqlserver “利用FTP下载然后bcp方式导入数据到数据库”
- HOW TO:利用Excel的QueryTable下载网上数据
- 利用Vista新技术WCF开发构建服务等几篇文章的源代码下载
- DOCSIS:有线电缆数据服务接口规范--网络大典
- 如果利用XMLHTTP.SEND提交并利用ASP在后台接收所提交数据
- 有线电缆数据服务接口规范(DOCSIS)--网络大典
- AJAX中利用POST方法向服务提交数据时乱码的解决方案
- 5G网络硬盘,100M文件大小,联想研究院发布联想社区化数据服务
- 使用 XSLT、KML 和 Google Maps API 在地图上覆盖数据,第 1 部分:利用 Google Geocoder Web 服务