android+后台下载notification,Android Service 后台下载

服务

importandroid.app.NotificationManager;importandroid.app.Service;importandroid.content.Context;importandroid.content.Intent;importandroid.net.Uri;importandroid.os.AsyncTask;importandroid.os.Environment;importandroid.os.IBinder;importandroid.support.v7.app.NotificationCompat;importandroid.util.Log;importandroid.widget.Toast;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.URL;importjava.net.URLConnection;/*** Created by dk on 2016/11/25.*/

public class DownloadSignatureService extendsService {protected static final String fileRootPath = Environment.getExternalStorageDirectory() +File.separator;protected static final String fileDownloadPath = "sunrise/download/";protected int fileSzie;//文件大小

protected int fileCache;//文件缓存

protected String fileName = "";//文件名

protected String fileNametemp = "";//临时文件

protected String urlStr = "";//下载url

protectedFile downloaddir, downloadfile, downloadfiletemp;protected staticNotificationManager mNotifyManager;protected staticNotificationCompat.Builder mBuilder;protected static final int notifiID = 0x000;protected static final String TAG = "LLL::";

@OverridepublicIBinder onBind(Intent intent) {return null;

}

@Overridepublic voidonCreate() {super.onCreate();

}

@Overridepublic int onStartCommand(Intent intent, int flags, intstartId) {

Log.e(TAG,"onStartCommand");

urlStr= (String) intent.getExtras().get("signatureurl");

Log.e(TAG,"urlStr = " +urlStr);/*Signature Download Url*/DownloadFile(urlStr);return super.onStartCommand(intent, flags, startId);

}

@Overridepublic voidonDestroy() {

Log.e(TAG,"onDestroy");super.onDestroy();

}/*** Download Signature

*

*@paramdownloadUrl*/

protected voidDownloadFile(String downloadUrl) {

Log.e(TAG,"DownloadFile");/*文件名*/fileName= downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1);/*缓存文件*/fileNametemp= "download.tmp";/*下载目录*/downloaddir= new File(fileRootPath +fileDownloadPath);

downloadfile= new File(fileRootPath + fileDownloadPath +fileName);

downloadfiletemp= new File(fileRootPath + fileDownloadPath +fileNametemp);if (!downloaddir.exists()) {

downloaddir.mkdirs();

}/*如何文件存在 这安装文件*/

if(downloadfile.exists()) {

installApp(DownloadSignatureService.this, fileRootPath + fileDownloadPath +fileName);

}/*否则下载文件*/

else{

mNotifyManager=(NotificationManager) DownloadSignatureService.this.getSystemService(DownloadSignatureService.this.NOTIFICATION_SERVICE);

mBuilder= new NotificationCompat.Builder(DownloadSignatureService.this);

mBuilder.setContentTitle("下载 电子签名App")

.setContentText("正在下载···")

.setProgress(100, 0, false)

.setSmallIcon(android.R.drawable.stat_sys_download);//downloadfile

new AsyncTask() {

@Overrideprotected voidonPreExecute() {

mBuilder.setTicker("下载电子签名").setProgress(100, 0, false);

mNotifyManager.notify(notifiID, mBuilder.build());super.onPreExecute();

}

@Overrideprotected voidonProgressUpdate(Integer... values) {

Log.e(TAG,"---下载缓存" + values[0] + "---");int pp = ((values[0] + 1) * 100 /fileSzie);

mBuilder.setProgress(100, pp, false).setContentText("已下载" + pp + "%");

mNotifyManager.notify(notifiID, mBuilder.build());super.onProgressUpdate(values);

}

@OverrideprotectedString doInBackground(String... params) {try{

fileName= params[0].substring(params[0].lastIndexOf("/") + 1);

Log.e("LLL", "---fileName = " +fileName);//获取文件名

URL myURL = new URL(params[0]);

URLConnection conn=myURL.openConnection();

conn.setDoInput(true);

conn.connect();

InputStream is=conn.getInputStream();

fileSzie= conn.getContentLength();//根据响应获取文件大小

if (fileSzie <= 0) {throw new RuntimeException("无法获知文件大小 ");

}if (is == null) throw new RuntimeException("stream is null");/*下载目录*/

if (!downloaddir.exists()) {

downloaddir.mkdirs();

}//把数据存入 路径+文件名

FileOutputStream fos = newFileOutputStream(downloadfiletemp);byte buf[] = new byte[1024];

fileCache= 0;do{//循环读取

int numread =is.read(buf);if (numread == -1) {break;

}

fos.write(buf,0, numread);

fileCache+=numread;this.publishProgress(fileCache);

}while (true);try{

is.close();

}catch(Exception ex) {

Log.e("tag", "error: " +ex.getMessage());

}

}catch(IOException e) {

e.printStackTrace();

}return "下载成功";

}

@Overrideprotected voidonPostExecute(String s) {/*下载成功后*/

if(downloadfiletemp.exists()) {

downloadfiletemp.renameTo(downloadfile);

}

Toast.makeText(DownloadSignatureService.this, s, Toast.LENGTH_SHORT).show();/*取消通知*/mBuilder.setContentText(s).setProgress(100, 0, false);

mNotifyManager.cancel(notifiID);

installApp(DownloadSignatureService.this, fileRootPath + fileDownloadPath +fileName);/*service kill 自杀*/DownloadSignatureService.this.stopSelf();super.onPostExecute(s);

}

}.execute(downloadUrl);

}

}/*** install Apk

*

*@paramcontext

*@paramfilePath*/

public voidinstallApp(Context context, String filePath) {

File _file= newFile(filePath);

Intent intent= newIntent(Intent.ACTION_VIEW);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.setDataAndType(Uri.fromFile(_file),"application/vnd.android.package-archive");

context.startActivity(intent);

}

}

启动服务

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值