標籤:
聲明:
//通知管理器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(); } } } }
android 通知(1)