Service与Notification的结合使用实现文件下载

import java.io.File;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;


import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.mine.ohter.R;
import com.mine.ohter.broadcast.InstallApkBroadcast;
import com.mine.ohter.utils.CommonUtil;
import com.mine.ohter.utils.FileUtils;


public class UpdataService extends Service {


private Notification notification;
private NotificationManager notificationManager;
private HttpUtils hu;
private String APKURL;
private String APKNAME = "hncy.apk";


private String wj = "https://download.alicdn.com/wireless/taobao4android/latest/702757.apk?spm=0.0.0.0.5dKpUK&file=702757.apk";
private static final int NOTIFICATION_ID = 0x12;


private DownLoadAPKListener downLoadListener;


public void setDownLoadListener(DownLoadAPKListener downLoadListener) {
this.downLoadListener = downLoadListener;
}


@Override
public IBinder onBind(Intent intent) {
return new MsgBinder();
}


@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}


@Override
public void onCreate() {
Log.i("mine", "onCreate");
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
hu = new HttpUtils();


}


private void initData() {
Log.i("mine", "服务开始");
if (CommonUtil.hasSdcard()) {
APKURL = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/js/" + APKNAME;
} else {
// 如果没有外置存储卡,就放到内置存储卡中
}
notification = new Notification();
notification.icon = R.drawable.ic_log;
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.tickerText = "开始下载";
remoteViews = new RemoteViews(getPackageName(), R.layout.test);
remoteViews.setImageViewResource(R.id.iv_down_load_icon,
R.drawable.ic_log);
remoteViews.setTextViewText(R.id.tv_app_name,
getResources().getString(R.string.app_name));
remoteViews.setTextViewText(R.id.tv_download_time,
CommonUtil.formatDateHour());
notification.contentView = remoteViews;
intentInstal = new Intent(UpdataService.this, InstallApkBroadcast.class);
intentInstal.putExtra("filepath", APKURL);
// intentInstal.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intentInstal.addCategory(Intent.CATEGORY_DEFAULT);
PendingIntent pi = PendingIntent.getBroadcast(UpdataService.this, 0,
intentInstal, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.contentIntent = pi;
downLoadFile(wj);


}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("mine", "onStartCommand");
if (!new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/js/" + "hncy.apk").exists()) {
initData();


} else {
boolean isSuccess = FileUtils.deleteFile(new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/js/"
+ "hncy.apk"));
Log.i("mine", "删除成功" + isSuccess);
if (isSuccess) {
initData();
}
}
return super.onStartCommand(intent, flags, startId);


}


@Override
public void onDestroy() {
Log.i("mine", "服务停止");
super.onDestroy();
}


/**
* 进行文件的下载

* @param url
*/
private void downLoadFile(String url) {
Log.i("mine", "开始下载");
hu.download(url, APKURL, // 文件的保存路径
true,// 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
true,// 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
downLoad);


}


private RequestCallBack<File> downLoad = new RequestCallBack<File>() {


@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
// 1.下载成功后进行点击安装
Log.i("mine", "下载完成");
sendBroadcast(intentInstal);
// removeNotifycation();


}


@Override
public void onFailure(HttpException error, String msg) {
// 下载失败后提示它重新下载
Log.i("mine", "下载失败");
}


@Override
public void onLoading(long total, long current, boolean isUploading) {
// 更新notification的进度,显示进度
Log.i("mine", "总大小" + total + "目前的进度" + current * 100 / total
+ "是否在下载" + isUploading);
int progress = (int) (current * 100 / total);
remoteViews.setProgressBar(R.id.pb_download, 100, progress, false);
remoteViews.setTextViewText(R.id.tv, progress + "%");
downLoadListener.downLoadProcess((int) total, progress);
notificationManager.notify(NOTIFICATION_ID, notification);


}


};
private RemoteViews remoteViews;
private Intent intentInstal;


/**
* 安装apk

* @param t
*/
private void installAPK(File t) {
// 进行安装
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(Uri.fromFile(t),
"application/vnd.android.package-archive");
startActivity(intent);
}


private void removeNotifycation() {
notificationManager.cancel(NOTIFICATION_ID);
}


public interface DownLoadAPKListener {
void downLoadProcess(int total, int current);
}


public class MsgBinder extends Binder {
/**
* 获取当前Service的实例

* @return
*/
public UpdataService getService() {
return UpdataService.this;
}


}


}

down_load_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/gray_background" >


    <ImageView
        android:id="@+id/iv_down_load_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true" 
        android:padding="4dp"
        />


    
    
    <ProgressBar
        android:layout_toRightOf="@id/iv_down_load_icon"
        android:id="@+id/pb_download"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="2dp"
        android:max="100" >
    </ProgressBar>


    <TextView
        android:id="@+id/tv"
        android:layout_alignParentRight="true"
        android:layout_below="@id/iv_down_load_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FF0000"
        android:layout_marginRight="8dp"
        android:text="进度"
        android:textSize="16sp" />


</RelativeLayout>



下载文件是使用了xutils开源框架进行下载  然后可以通过bindService的方式可以获取这个Service对象,实现接口,获取下载的进度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值