23 服务IntentService Demo6
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的更多相关文章
- 服务 IntentService 前台服务 定时后台服务
Activity public class MainActivity extends ListActivity { private int intentNumber = 0; @Ove ...
- 23 服务的启动Demo2
MainActivity.java package com.qf.day23_service_demo2; import android.app.Activity; import android.co ...
- 更加省心的服务,IntentService的使用
通过前两篇文章的学习,我们知道了服务的代码是默认运行在主线程里的,因此,如果要在服务里面执行耗时操作的代码,我们就需要开启一个子线程去处理这些代码.比如我们可以在 onStartCommand方法里面 ...
- 23 服务音乐的启动Demo4
注意如果音乐服务和Activity在一个应用中那么将不会因为绑定的Activity销毁而关闭音乐 MainActivity.java package com.qf.day23_service_demo ...
- 23 服务的绑定启动Demo3
MainActivity.java package com.example.day23_service_demo3; import com.example.day23_service_demo3.My ...
- 23 服务的创建Demo1
结构 MainActivity.java package com.qf.day23_service_demo1; import android.app.Activity; import android ...
- C#开发BIMFACE系列23 服务端API之获取模型数据8:获取模型链接信息
系列目录 [已更新最新开发文章,点击查看详细] 在Revit等BIM设计工具中可以给模型的某个部位添加链接信息.即类似于在Office Word.Excel 中给一段文字添加本地文件链接或者网 ...
- IntentService 服务 工作线程 stopself MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- Android服务(Service)研究
Service是android四大组件之一,没有用户界面,一直在后台运行. 为什么使用Service启动新线程执行耗时任务,而不直接在Activity中启动一个子线程处理? 1.Activity会被用 ...
随机推荐
- leetcode 561.Array Partition I-easy
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1 ...
- 手动导入xmpp后,再使用cocoapods的时候出现的问题
最新的cocoapod导入xmpp的时候,会出现循环依赖,所以撸主选择了手动导入. 一开始还用的挺开心的,后来,使用cocoapods导入其他的框架,发现调用的时候总是报错. Undefined sy ...
- Kylin系列之二:原理介绍
Kylin系列之二:原理介绍 2018年4月15日 15:52 因何而生 Kylin和hive的区别 1. hive主要是离线分析平台,适用于已经有成熟的报表体系,每天只要定时运行即可. 2. Kyl ...
- cmseasy CmsEasy_5.6_20151009 无限制报错注入(parse_str()的坑)
来源:http://wooyun.jozxing.cc/static/bugs/wooyun-2015-0137013.html parse_str()引发的注入, //parse_str()的作用是 ...
- github学习(三)
Git学习(二) 分支学习: 创建新分支dev:git branch dev 切换到dev分支:git checkout dev 可以简写为一句话:git checkout -b dev 可以用命令g ...
- [SDOI 2010]外星千足虫
Description 题库链接 给出 \(m\) 个 \(n\) 元的 \(0,1\) 方程,即系数非 \(0\) 即 \(1\) ,方程的结果为奇偶性. \(1\leq n\leq 1000,1\ ...
- [测试题]gentree
Description 给你一个有向连通图G,每点有个权值Di(0<Di),要求生成一棵树根为1号节点的有根树T.对于树中边E,E的代价为所有从根出发的且包含E的路径的终点权值的和.现求生成树T ...
- ●BZOJ 1797 [Ahoi2009]Mincut 最小割
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=1797 题解: 详细的讲解去看http://hzwer.com/3217.html首先跑一个最 ...
- Hdu 5595 GTW likes math
题意: 问题描述 某一天,GTW听了数学特级教师金龙鱼的课之后,开始做数学<从自主招生到竞赛>.然而书里的题目太多了,GTW还有很多事情要忙(比如把妹),于是他把那些题目交给了你.每一道题 ...
- [bzoj4881][Lydsy2017年5月月赛]线段游戏
来自FallDream的博客,未经允许,请勿转载,谢谢. quailty和tangjz正在玩一个关于线段的游戏.在平面上有n条线段,编号依次为1到n.其中第i条线段的两端点坐标分别为(0,i)和(1, ...