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] Monotone Increasing Digits 单调递增数字

    Given a non-negative integer N, find the largest number that is less than or equal to N with monoton ...

  2. org.apache.commons.lang3.tuple.Pair 作为更新参数,XML 中的 Sql 取不到值、报错

    项目用的 Mybatis,今天改一个需求,落地实现是批量更新,且只需要根据主键(id)来更新一个字段(name). 于是,没有犹豫,像下面这样设计了数据结构: 既然是批量更新,那外层肯定是 List ...

  3. pdf如何转换为word文档

    我们经常会遇到需要将PDF转换为WORD文档,对于我来讲,有些PDF没有目录,看起来非常不方便,于是就特别想转成WORD,然后增加目录,想看某一节内容时,快速查找. 这里我总结了一些方法,后续也会不断 ...

  4. codevs 1006 等差数列

    提交地址:http://codevs.cn/problem/1006/ 1006 等差数列  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold   题目描述 Des ...

  5. [HNOI2016]大数

    题目描述 小 B 有一个很大的数 S,长度达到了 N 位:这个数可以看成是一个串,它可能有前导 0,例如00009312345.小B还有一个素数P.现在,小 B 提出了 M 个询问,每个询问求 S 的 ...

  6. ●BZOJ 1531 [POI2005]Bank notes

    题链: http://www.lydsy.com/JudgeOnline/problem.php?id=1531 题解: 单调队列优化多重背包DP (弱弱的我今天总算是把这个坑给填了...) 令V[i ...

  7. [bzoj4823][Cqoi2017]老C的方块

    来自FallDream的博客,未经允许,请勿转载,谢谢. 挺有意思的一道题.... 看完题面比较明确是最小割,考虑怎么建图 想了比较久 突破口应该是题目中那张奇怪的图 观察这个奇怪的图和方块,很容易发 ...

  8. VK-Cup2017 Wild Card Round 2

    来自FallDream的博客,未经允许,请勿转载,谢谢. Cf的Vkcup外卡赛2  上次round2和ditoly翻车了 所以只好来打打了  规则是给一道比较特殊的题目,你要找出较优的解 Unive ...

  9. ubuntu上的附件-终端和用快捷键ctrl+alt+f1 有啥区别

    ctrl +alt +Fn 打开的是模拟终端,简单说来,linux系统一开机会自动打开6个模拟终端,然后自动切换到其中一个(一般来说是切换到图形界面的那个也就是说窗口管理器是在这6个模拟终端中运行的) ...

  10. 数据结构之B树、B+树(一)

    B-树 什么是B-树? B树是一种查找树,我们知道,这一类树(比如二叉搜索树,红黑树等等)最初生成的目的都是为了解决某种系统中,查找效率低的问题.B树也是如此,它最初启发于二叉搜索树,二叉搜索树的特点 ...