MainActivity.java

package com.qf.day23_service_demo2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View; public class MainActivity extends Activity { private String iamgUrl = "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=2507878052,3446525205&fm=58"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} //点击按钮 开启服务下载数据
public void MyLoadClick(View v){ Intent intent = new Intent();
intent.setAction("com.qf.day23_service_demo2.MyLoaderService");
intent.putExtra("imagUrl", iamgUrl);
startService(intent); }
//点击按钮 停止服务
public void StopServiceClick(View v){
Intent intent = new Intent();
intent.setAction("com.qf.day23_service_demo2.MyLoaderService");
stopService(intent); } }

MyLoaderService.java

package com.qf.day23_service_demo2;

import com.qf.day23_service_demo2.utils.FileUtils;
import com.qf.day23_service_demo2.utils.HttpUtils; import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log; public class MyLoaderService extends IntentService { String imagUrl = ""; public MyLoaderService(String name) {
super(name);
// TODO Auto-generated constructor stub
} public MyLoaderService() {
super("");
// TODO Auto-generated constructor stub
} // 开启了线程
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
imagUrl = intent.getStringExtra("imagUrl");
// 开启下载 // 判断网络状态
if (HttpUtils.isNetWork(MyLoaderService.this)) {
// 开始下载
byte[] buffer = HttpUtils.getData(imagUrl);
// 保存在SD卡
if (FileUtils.isConnSdCard()) {
// 保存到 Sd卡
boolean flag = FileUtils.writeToSdcard(buffer, imagUrl);
if (flag) {
Log.e("AAA", "下载完成");
// 发送广播
sendNotification();
// 服务自己关闭服务
stopSelf();
} } else {
Log.e("AAA", "Sd卡不可用");
} } else {
Log.e("AAA", "网络异常");
} } // 发送广播
public void sendNotification() { // 要传递的图片名称
imagUrl = imagUrl.substring(imagUrl.lastIndexOf("/") + 1); NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext());
builder.setContentTitle("下载美女图");
builder.setContentText("景甜");
builder.setSmallIcon(R.drawable.ic_launcher); Intent intent = new Intent(MyLoaderService.this, SecondActivity.class);
intent.putExtra("imagUrl", imagUrl);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 100, intent,
PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(pendingIntent); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
} }

SecondActivity.java

package com.qf.day23_service_demo2;

import java.io.File;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView; public class SecondActivity extends Activity { private ImageView iv; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState); setContentView(R.layout.layout);
iv = (ImageView) findViewById(R.id.iv); String imagUrl = getIntent().getStringExtra("imagUrl"); File file = new File(Environment.
getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), imagUrl); String pathName = file.getAbsolutePath(); Bitmap bp = BitmapFactory.decodeFile(pathName); iv.setImageBitmap(bp);
} }

FileUtils.java

package com.qf.day23_service_demo2.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import android.os.Environment; public class FileUtils { /**
* 判断sdCard是否挂载
* @return
*/
public static boolean isConnSdCard(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
/**
* 将图片的字节数组保存到 sd卡上
* @return
*/
public static boolean writeToSdcard(byte[] buffer ,String imagName){
FileOutputStream outputStream =null; boolean flag = false; String fileName = imagName.substring(imagName.lastIndexOf("/")+1);
File file = new File(Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
try { outputStream = new FileOutputStream(file);
outputStream.write(buffer);
flag = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} return flag; } }

HttpUtils.java

package com.qf.day23_service_demo2.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo; public class HttpUtils {
/**
* 判断是否有网络
* @param context
* @return
*/
public static boolean isNetWork(Context context){
//得到网络的管理者
ConnectivityManager manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo(); if(info!=null){
return true; }else{
return false;
} } /**
* 获取数据
* @param path
* @return
*/
public static byte[] getData(String path) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int temp = 0;
while ((temp = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, temp);
outputStream.flush();
} }
return outputStream.toByteArray(); } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null; } }

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qf.day23_service_demo2"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.qf.day23_service_demo2.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"></activity>
<service android:name=".MyLoaderService">
<intent-filter >
<action android:name="com.qf.day23_service_demo2.MyLoaderService"/>
</intent-filter>
</service>
</application> </manifest>

23 服务IntentService Demo6的更多相关文章

  1. 服务 IntentService 前台服务 定时后台服务

    Activity public class MainActivity extends ListActivity {     private int intentNumber = 0;     @Ove ...

  2. 23 服务的启动Demo2

    MainActivity.java package com.qf.day23_service_demo2; import android.app.Activity; import android.co ...

  3. 更加省心的服务,IntentService的使用

    通过前两篇文章的学习,我们知道了服务的代码是默认运行在主线程里的,因此,如果要在服务里面执行耗时操作的代码,我们就需要开启一个子线程去处理这些代码.比如我们可以在 onStartCommand方法里面 ...

  4. 23 服务音乐的启动Demo4

    注意如果音乐服务和Activity在一个应用中那么将不会因为绑定的Activity销毁而关闭音乐 MainActivity.java package com.qf.day23_service_demo ...

  5. 23 服务的绑定启动Demo3

    MainActivity.java package com.example.day23_service_demo3; import com.example.day23_service_demo3.My ...

  6. 23 服务的创建Demo1

    结构 MainActivity.java package com.qf.day23_service_demo1; import android.app.Activity; import android ...

  7. C#开发BIMFACE系列23 服务端API之获取模型数据8:获取模型链接信息

    系列目录     [已更新最新开发文章,点击查看详细] 在Revit等BIM设计工具中可以给模型的某个部位添加链接信息.即类似于在Office Word.Excel 中给一段文字添加本地文件链接或者网 ...

  8. IntentService 服务 工作线程 stopself MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  9. Android服务(Service)研究

    Service是android四大组件之一,没有用户界面,一直在后台运行. 为什么使用Service启动新线程执行耗时任务,而不直接在Activity中启动一个子线程处理? 1.Activity会被用 ...

随机推荐

  1. [LeetCode] Squirrel Simulation 松鼠模拟

    There's a tree, a squirrel, and several nuts. Positions are represented by the cells in a 2D grid. Y ...

  2. PHPCMS v9.6.0 任意文件上传漏洞分析

    引用源:http://paper.seebug.org/273/ 配置了php debug的环境,并且根据这篇文章把流程走了一遍,对phpstorm的debug熟练度+1(跟pycharm一样) 用户 ...

  3. [IOI2007]训练路径

    Description 马克(Mirko)和斯拉夫克(Slavko)正在为克罗地亚举办的每年一次的双人骑车马拉松赛而紧张训练.他们需要选择一条训练路径. 他们国家有N个城市和M条道路.每条道路连接两个 ...

  4. hdu 5430(几何)

    题意:求光在圆内反射n次后第一次返回原点的方案数 如果k和n-1可约分,则表明是循环多次反射方案才返回原点. #include <iostream> #include <cstrin ...

  5. [ Java学习基础 ] Java构造函数

    构造方法是类中特殊方法,用来初始化类的实例变量,它在创建对象(new运算符)之后自动调用. Java构造方法的特点如下: 构造方法名必须与类名相同. 构造方法没有任何返回值,包括void. 构造方法只 ...

  6. 【完整项目】使用Scrapy模拟HTTP POST,获取完美名字

    1. 背景 最近有人委托我给小孩起个名字,说名字最好符合周易五行生克理论,然后给了我个网址,说像是这个网站中的八字测名,输入名字和生辰八字等信息,会给出来这个名字的分数和对未来人生的预测.当父母的自然 ...

  7. 对I/O设备分配的一般策略是什么?

    策略是:独享分配.共享分配.虚拟分配 补充:I/O设备的分配算法 1.  先请求先服务 2.  优先级最高者优先

  8. JAVA NIO工作原理及代码示例

    简介:本文主要介绍了JAVA NIO中的Buffer, Channel, Selector的工作原理以及使用它们的若干注意事项,最后是利用它们实现服务器和客户端通信的代码实例. 欢迎探讨,如有错误敬请 ...

  9. SynchronizedMap和ConcurrentHashMap的深入分析

    http://blog.sina.com.cn/s/blog_5157093c0100hm3y.html java5中新增了ConcurrentMap接口和它的一个实现类ConcurrentHashM ...

  10. JVM指令集介绍

    转载自:http://glutinit.iteye.com/blog/1263446 延伸参考 JVM接收参数和方法调用 void spin() {    int   i;    for (i = 0 ...