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

来源:互联网 发布:初学者吉他推荐知乎 编辑:程序博客网 时间:2024/05/13 17:50

使用启动式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";@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {//service是运行在UI主线程上的,不能用http直接访问网络 final Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);if(msg.what==1){stopSelf();// 关闭service服务Toast.makeText(getApplicationContext(), "文件下载完毕!", 1).show();}} }; new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubHttpClient 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 exceptione.printStackTrace();}finally{if(outputStream!=null){try {outputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(httpClient!=null){httpClient.getConnectionManager().shutdown();}}}}).start(); return super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button=(Button)findViewById(R.id.button1);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubIntent intent=new Intent(MainActivity.this,DownLoadService.class);startService(intent);//启动service}});}@Overridepublic 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;}}




1 0