MainActivity.java

package com.qf.day23_service_demo2;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView; public class MainActivity extends Activity { private String iamgUrl = "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=2507878052,3446525205&fm=58";
private TextView tv; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){ @Override
public void onReceive(Context context, Intent intent) { tv.setText("去死吧");
Log.e("fmy", "嘿嘿");
} };
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("fmy.fmy.fmy");
registerReceiver(broadcastReceiver, intentFilter);
} //点击按钮 开启服务下载数据
public void MyLoadClick(View v){ Intent intent = new Intent();
intent.setAction("com.qf.day23_service_demo2.MyLoaderService");
intent.putExtra("imagUrl", iamgUrl);
//API 23以上需要加上 不然报错
// intent.setPackage(getPackageName());
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.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 Service{ String imagUrl =""; @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
imagUrl = intent.getStringExtra("imagUrl");
//开启下载
new Thread(){
public void run() {
//判断网络状态
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();
Intent intent2 = new Intent("fmy.fmy.fmy");
sendBroadcast(intent2);
//服务自己关闭服务
stopSelf();
} }else{
Log.e("AAA", "Sd卡不可用");
} }else{
Log.e("AAA", "网络异常");
} };
}.start();
return super.onStartCommand(intent, flags, startId);
} //发送广播
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; } }

AndroidManifest.xml

<?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="com.qf.day23_service_demo2.MyLoaderService">
<intent-filter >
<action android:name="com.qf.day23_service_demo2.MyLoaderService"/>
</intent-filter>
</service>
</application> </manifest>

最新文章

  1. python Chrome 开发者模式消失的方法
  2. MySQL Python教程(3)
  3. 【原】iOS学习之XMPP环境搭建
  4. 记录php日志
  5. tesseract-ocr了解
  6. ubuntu 12.10无法用apt-get安装软件 Err http://us.archive.ubuntu.com quantal-updates/main Sources 404 Not
  7. java中ReentrantReadWriteLock读写锁的使用
  8. [MySQL-1] mysql error 1101 blob/text column can&#39;t have a default value
  9. python学习随笔
  10. XML文档部署到Tomcat服务器上总是加载出错
  11. C# 通过Attribute制作的一个消息拦截器
  12. About struct in C
  13. 2016.3.17__CSS3动画__第十一天
  14. Problem : 1196 ( Lowest Bit )
  15. orcal - 增删改
  16. 使用flask_socketio实现服务端向客户端定时推送
  17. ABBYY OCR技术教电脑阅读缅甸语(上)
  18. python day02 作业答案
  19. python 3使用binascii方法的报错解决
  20. UML学习归纳整理

热门文章

  1. Python系列之 - python循环语句
  2. Python模块之 - logging
  3. PHPCMS某处设计缺陷可致authkey泄露
  4. [POJ 2248]Addition Chains
  5. [POI2016]Nim z utrudnieniem
  6. 【线段树】【BZOJ1798】【AHOI2009】维护序列
  7. 【USACO17JAN】Promotion Counting晋升者计数 线段树+离散化
  8. poj 2318 叉积+二分
  9. POJ 3171 Cleaning Shifts
  10. [BZOJ]1042 硬币购物(HAOI2008)