加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:25:18 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 /** * service运行在主线程里所以不能使用HTTP协议访问网络 * * try catch的实例尽量在该块外面定义 */public class MyService extends Service { pub

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

/**

 * 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,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;

}

 

}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读