标签:
声明:
//通知管理器
private NotificationManager nmanager;
// 统治构造器
private Notification.Builder builder ;
通知初始化
/**
*通知初始化
*/
private void getNotification() {
//通知管理器
nmanager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);//系统通知
//通过构造器设置通知的标题和内容
builder = new Notification.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker("通知来了");//提示标题
builder.setContentTitle("下载"); //通知内容标题
builder.setContentText("正在下载。。。。。");//通知内容
}
通知进度更新
/**
* 更新UI
*/
private Handler handler = new Handler() {
public void handleMessage(Message msg) {//接收线程发送来的消息
//更新UI
builder.setProgress(100, msg.arg1, false);
//1001是该通知的唯一编号,可以调用nmanager.cancel(1001);注销这个通知
nmanager.notify(1001, builder.build());
if(msg.what == 1){
//下载完成
String name = uri.split("/")[-1];
builder.setContentTitle(name);
builder.setContentText("下载完成");
Toast.makeText(getApplicationContext(), "下载完成", 1).show();
}
}
};
/** * 下载放在线程中执行, * */ public class MyRunnable implements Runnable { @Override public void run() { //读取的数据存储 byte[] result = null; HttpClient client = new DefaultHttpClient(); try { Log.i("tag", "uri>>"+uri); HttpGet get = new HttpGet(uri); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); int stateCode = response.getStatusLine().getStatusCode(); if(stateCode != 200){ Log.i("tag", stateCode+"-->下载失败-->"); } //获取网络输入流 InputStream in = entity.getContent(); //获取网路数据总长度 long total = entity.getContentLength(); byte[] bs = new byte[256]; int len_per = 0;//每次读取的长度, ByteArrayOutputStream baos = new ByteArrayOutputStream(); int readedLen = 0;//已经读取的数据量 while((len_per = in.read(bs)) != -1){ baos.write(bs, 0, len_per); readedLen += len_per; int progress = (int) ((readedLen*100)/(float)total); Message msg = Message.obtain(); msg.arg1 = progress; handler.sendMessage(msg); } result = baos.toByteArray(); handler.sendEmptyMessage(1); }catch(Exception e){ e.printStackTrace(); }finally { if(client != null){ client.getConnectionManager().shutdown(); } } } }
标签:
原文地址:http://www.cnblogs.com/chengbao/p/5616444.html