安卓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
- 安卓Service组件使用系列2:使用Service下载网络图片并存储于sdCard卡上
- 安卓Service组件使用系列3:使用IntentService下载网络图片
- 使用Service服务下载网络图片并写入sdCard
- 安卓Service组件使用系列4:绑定service并调用service中的方法返回结果
- 安卓Service组件使用系列1:启动式Service的生命周期
- 安卓Service组件使用系列5:service和activity之间的数据交互
- 使用Service下载图片并发送通知读取图片内容
- 安卓Service组件使用系列6:使用AIDL完成两个进程间的通信
- 使用Service实现网络音乐下载并播放
- 安卓:启动service,下载网络图片,并将图片存放到内存卡,保存成功后发出广播提醒,然后从SD卡读出显示
- 安卓 Service组件
- 安卓开发-Service使用
- 安卓多线程编程系列3:使用handler和message下载网络图片
- 安卓组件之Service
- 61 Android Service 下载图片保存到Sdcard
- 安卓多线程编程系列1:异步任务的使用之使用异步任务圆圈滚动条下载网络图片
- 安卓网络下载图片picasso的使用
- 安卓控件使用系列17:ImageView获取网络图片
- 请慎用java的File#renameTo(File)方法
- springMVC配置一
- 编程式事务和声明式事务
- 求解两个字符串的最长公共子串
- 分享的好处
- 安卓Service组件使用系列2:使用Service下载网络图片并存储于sdCard卡上
- 遗传算法入门到掌握(一)
- iOS 原生扫描二维码
- UIButton 九宫格的封装
- android 网络判断是否可用
- 在linux下向U盘复制文件时发生错误,显示目标是只读的,windows下能够正常使用,应该怎么解决?
- 4.10 使用Vitamio打造自己的Android万能播放器(2)—— 手势控制亮度、音量、缩放
- Hibernate的packagesToScan路径解析分析
- Mongodb 在windwos下安装