80,349
社区成员
发帖
与我相关
我的任务
分享
public class CustomProgressNoticeActivity extends Activity {
private Button button1;
private ImageView imageView;
private NotificationCompat.Builder mBuilder;
private NotificationManager mNotificationManager;
private int id = 1000;
private RemoteViews contentViews;
private String picPath = "http://pic1a.nipic.com/2008-11-12/2008111215916645_2.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_progress_notice);
button1 = (Button) findViewById(R.id.button1);
imageView = (ImageView) findViewById(R.id.imageView1);
contentViews = new RemoteViews(getPackageName(), R.layout.notice_download);
// 通过控件的Id设置属性
contentViews.setImageViewResource(R.id.imageNo, R.drawable.ic_launcher);
contentViews.setTextViewText(R.id.tv_title, "图片下载");
mBuilder = new NotificationCompat.Builder(CustomProgressNoticeActivity.this).setSmallIcon(R.drawable.ic_launcher).setTicker("图片下载...");
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setContent(contentViews);
mBuilder.setAutoCancel(true);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new DownImage().execute(picPath);
}
});
}
class DownImage extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
Bitmap bitmap = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
input = httpResponse.getEntity().getContent();
byte data[] = new byte[1024];
long fileLength = httpResponse.getEntity().getContentLength();
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
bos.write(data, 0, count);
}
}
bos.flush();
byte[] imgBytes = bos.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
// mBuilder.setDefaults(Notification.DEFAULT_SOUND);
}
@Override
protected void onProgressUpdate(Integer... values) {
contentViews.setProgressBar(R.id.pb_download, 100, values[0], false);
contentViews.setTextViewText(R.id.tv_currentPos, values[0] + "%");
mNotificationManager.notify(id, mBuilder.build());
}
@Override
protected void onPreExecute() {
contentViews.setProgressBar(R.id.pb_download, 100, 0, false);
contentViews.setTextViewText(R.id.tv_currentPos, "0%");
mNotificationManager.notify(id, mBuilder.build());
}
}
}