服务
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);
}
}
启动服务