您的位置:首页 > 理论基础 > 计算机网络

安卓Service组件使用系列2:使用Service下载网络图片并存储于sdCard卡上

2016-03-08 10:41 585 查看
使用启动式Service的方式可以处理网络的数据交互、音乐播放、执行IO操作(这些操作都是来自后台的)。下面我们以下载网络图片并存储于sdCard卡为实际应用背景来说明它的使用方法。

整体思路:在xml文件中放置一个Button控件,在这个Button点击事件中启动Service。定义一个DownLoadService类继承Service,并在这个类中重写onCreate()、onStartCommand()、onDestory()三个方法,在onStartCommand方法中,定义一个线程,在这个线程的run方法中,下载网络图片、存储于scCard卡并使用handler发送携带what信息的消息,在handler中接收到what消息,检查一致则关闭Service并提示下载完毕。

activity_main.xml文件:

<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/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="104dp"
android:text="使用Service下载网络图片" />

</RelativeLayout>
DownLoadService.java文件:

package com.example.android_service_download;
//使用service下载网络图片并存储于sdCard卡(内置sd卡)上
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Service;
import android.content.Entity;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.Toast;

public class DownLoadService extends Service {
//  有些网络图片的地址是不允许访问的,下面这个网址是可以的
private final String  IMAGE_PATH="https://www.baidu.com/img/bd_logo1.png";
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//service是运行在UI主线程上的,不能用http直接访问网络
final Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what==1){
stopSelf();// 关闭service服务
Toast.makeText(getApplicationContext(), "文件下载完毕!", 1).show();
}
}
};
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(IMAGE_PATH);
HttpResponse response=null;
//				获得sdcard卡的目录
File file=Environment.getExternalStorageDirectory();
FileOutputStream outputStream=null;
try {
response=httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
//						获得了图片的内容
byte[] result=EntityUtils.toByteArray(response.getEntity());
//						判断sdcard卡是否挂载,并且可以存储数据
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File new_file=new File(file,"bd_logo1.png");
outputStream=new FileOutputStream(new_file);
outputStream.write(result, 0, result.length);
//							因为完成下载之后必须关闭service,所以要使用一个消息
Message message=Message.obtain();
message.what=1;
handler.sendMessage(message);//发送消息
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(outputStream!=null){
try {
outputStream.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 arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}

}
MainActivity.java文件:

package com.example.android_service_download;

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

public class MainActivity extends Activity {

private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,DownLoadService.class);
startService(intent);//启动service
}
});

}

@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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: