博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
23 服务IntentService Demo6
阅读量:5278 次
发布时间:2019-06-14

本文共 8255 字,大约阅读时间需要 27 分钟。

这里写图片描述

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; }}

清单文件

转载于:https://www.cnblogs.com/muyuge/p/6152182.html

你可能感兴趣的文章
redis学习笔记(二)
查看>>
luogu题解 P1099 【树网的核】树的直径变式+数据结构维护
查看>>
[持续更新]一些结论与技巧
查看>>
Java中的Random()函数
查看>>
多线程NSThread基本用法
查看>>
jstl-随机数-借用jsp嵌入的代码
查看>>
云变换算法
查看>>
C#创建socket服务
查看>>
小智慧38
查看>>
【译】x86程序员手册01
查看>>
CDI server decorstors intercepters scope EL eventmodel
查看>>
软件测试homework1
查看>>
第六次课程作业:随笔
查看>>
行列式,线性变换,变换,雅克比行列式,二次型
查看>>
文件写入和读取
查看>>
物理学中的几何方法笔记
查看>>
dtree实现动态加载树形菜单,动态插入树形菜单
查看>>
如何在java List中进行模糊查询
查看>>
定制一套属于自己的博客样式
查看>>
ArcGIS自定义工具箱-字段值部分替换
查看>>