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. ubuntu下安装foxi reader阅读器

    参考 :https://blog.csdn.net/u013831198/article/details/72472040 请参照以下步骤安装Foxit Reader(适用于Linux):   •   ...

  2. [CQOI 2015]选数

    Description 我们知道,从区间[L,H](L和H为整数)中选取N个整数,总共有(H-L+1)^N种方案.小z很好奇这样选出的数的最大公约数的规律,他决定对每种方案选出的N个整数都求一次最大公 ...

  3. [SHOI2008]小约翰的游戏John

    Description 小约翰经常和他的哥哥玩一个非常有趣的游戏:桌子上有n堆石子,小约翰和他的哥哥轮流取石子,每个人取 的时候,可以随意选择一堆石子,在这堆石子中取走任意多的石子,但不能一粒石子也不 ...

  4. bzoj5055 膜法师

    Description 在经历过1e9次大型战争后的宇宙中现在还剩下n个完美维度, 现在来自多元宇宙的膜法师,想偷取其中的三个维度为伟大的长者续秒, 显然,他能为长者所续的时间,为这三个维度上能量的乘 ...

  5. 区间(interval)

    [问题描述]给定 N 个区间, 要求选出若干个区间 A1, A2, A3... Am (m > 1), 使得:|A1∩A2∩A3...∩Am| * |A1∪A2∪A3...∪Am|最大.[输入格 ...

  6. WISCO信息组NOIP模拟赛-数据结构

    传送门 差分+暴力 #include<cstdio> #include<cstdlib> #include<algorithm> #include<cstri ...

  7. 【BZOJ4196】【Noi2015】软件包管理器

    原题传送门 题意: 给你一棵树,有2种操作: 1.使得某个点到根节点路径上的所有点权值赋为1. 2.使得某节点的子树中所有节点权值赋为0. 每次操作要求输出权值更改的节点个数. 解题思路: 显然是用树 ...

  8. ●POJ 1228 Grandpas Estate

    题链: http://poj.org/problem?id=1228 题解: 计算几何,凸包 题意:给出一些点,求出其凸包,问是否是一个稳定的凸包. 稳定凸包:不能通过新加点使得原来凸包上的点(包括原 ...

  9. [Russian Code Cup 2017 - Finals [Unofficial Mirror]]简要题解

    来自FallDream的博客,未经允许,请勿转载,谢谢. Div1难度+ACM赛制  和几个大佬组队逛了逛 A.给一个大小为n的集合ai(1<=ai<=1000000),要求你构造一个大小 ...

  10. 从零安装Scrapy心得 | Install Python Scrapy from scratch

    1. 介绍 Scrapy,是基于python的网络爬虫框架,它能从网络上爬下来信息,是data获取的一个好方式.于是想安装下看看. 进到它的官网,安装的介绍页面 https://docs.scrapy ...