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] Set Intersection Size At Least Two 设置交集大小至少为2
An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, ...
- electron通讯
Electron桌面应用实现两个窗口(渲染进程)之间的通讯,传输数据: 方法1:在两个网页(渲染进程)间共享数据最简单的方法是使用浏览器中已经实现的 HTML5 API. 其中比较好的方案是用 Sto ...
- 【Swift】swift中懒加载的写法
swift中懒加载的写法,直接上例子 (懒加载一个遮罩视图) lazy var dummyView: UIView = { let v = UIView() v.backgroundColor = U ...
- 集合之LinkedList源码分析
转载请注明出处:http://www.cnblogs.com/qm-article/p/8903893.html 一.介绍 在介绍该源码之前,先来了解一下链表,接触过数据结构的都知道,有种结构叫链表, ...
- Ubuntu 16下安装64位谷歌Chrome浏览器
Ubuntu 16下安装64位谷歌Chrome浏览器 1.将下载源加入到系统的源列表 在终端中,输入以下命令: sudo wget https://repo.fdzh.org/chrome/googl ...
- 《C++ Primer》学习笔记:向vector对象添加元素蕴含的编程假定
练习<C++ Primer>中的3.14节时,当敲入: #include <iostream> #include <string> using namespace ...
- [USACO 13DEC]Vacation Planning(gold)
Description Air Bovinia operates flights connecting the N farms that the cows live on (1 <= N < ...
- ●BZOJ 2588 Spoj 10628. Count on a tree
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=2588 题解: 主席树,在线,(求LCA)感觉主席树真的好厉害...在原树上建主席树.即对于原 ...
- BZOJ3065(替罪羊树套线段树)
以前看到这题都瑟瑟发抖,终于过了心情舒畅. 按下标为关键字建替罪羊树,每个结点开一个权值线段树,维护的这个结点代表的子树的信息. 这题还得垃圾回收,自己yy的,不知对不对.. #include < ...
- PTA 字符串关键字的散列映射(25 分)
7-17 字符串关键字的散列映射(25 分) 给定一系列由大写英文字母组成的字符串关键字和素数P,用移位法定义的散列函数H(Key)将关键字Key中的最后3个字符映射为整数,每个字符占5位:再用除留余 ...