您的位置:首页 > 移动开发 > Android开发

Android带下载进度条的通知栏

2015-06-04 14:38 639 查看
使用Servcie实现带下载进度条的通知栏,包含DownloadService、DownloadUtil两个类。

主程序调用:

Intent intent= new Intent(MainActivity.this, DownloadService.class);
startService(intent);


DownloadService:

public class DownloadService extends Service {
private Context mContext = this;
/** 正在下载 */
private final int DOWN_LOADING = 0;
/** 下载完成 */
private final int DOWN_COMPLETE = 1;
/** 下载失败 */
private final int DOWN_ERROR = 2;
/** Timer 执行时间间隔 */
private final int TIMER_PERIOD = 500;

private final int NOTIFY_ID = 0;

protected Timer mTimer;
protected NotificationManager mNotificationManager;
private Notification mNotification = null;
private int appname = 0;
private String downurl = "";

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
appname = R.string.app_name;
downurl = "下载地址";
mNotification = new Notification.Builder(this).build();
mNotification.icon = R.drawable.ic_launcher;
mNotification.tickerText = getResources().getString(appname);
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotification.contentView = new RemoteViews(mContext.getPackageName(),
R.layout.download_view);

Intent updateIntent = new Intent(this, MainActivity.class);
updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(mContext, 0,
updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.contentIntent = pIntent;
mNotificationManager.notify(NOTIFY_ID, mNotification);

new Thread(new updateRunnable()).start();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

class updateRunnable implements Runnable {
private DownloadUtil mDownUtil = new DownloadUtil();
private Handler mHandler;
private TimerTask mTimerTask;

public updateRunnable() {
super();
this.mHandler = new MyHandler(mDownUtil);
this.mTimerTask = new MyTimerTask(mDownUtil, mHandler);
}

@Override
public void run() {
mTimer.schedule(mTimerTask, 0, TIMER_PERIOD);
mDownUtil.downloadFile(downurl);
}
}

class MyTimerTask extends TimerTask {
private Handler mHandler;
private DownloadUtil mDownUtil;
private IOnDownloadListener mListener;

public MyTimerTask(DownloadUtil downUtil, Handler handler) {
super();
this.mHandler = handler;
this.mDownUtil = downUtil;
this.mListener = new IOnDownloadListener() {
@Override
public void updateNotification(int progress, int totalSize,
File downFile) {
int rate = 0;
if (totalSize > 0) {
rate = progress * 100 / totalSize;
mHandler.obtainMessage(DOWN_LOADING, rate, 0)
.sendToTarget();
} else if (totalSize == 0) {
mHandler.obtainMessage(DOWN_LOADING, 0, 0)
.sendToTarget();
} else {
cancel();
mHandler.obtainMessage(DOWN_ERROR).sendToTarget();
}
if (totalSize > 0 && null != downFile
&& totalSize == (int) downFile.length()) {
cancel();
mHandler.obtainMessage(DOWN_COMPLETE, downFile)
.sendToTarget();
}
}
};
}

@Override
public void run() {
mDownUtil.setOnDownloadListener(mListener);
}
}

@SuppressLint("HandlerLeak")
class MyHandler extends Handler {
private DownloadUtil mDownUtil;

public MyHandler(DownloadUtil downUtil) {
super();
this.mDownUtil = downUtil;
}

@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWN_LOADING:
mNotification.contentView.setProgressBar(R.id.progressBar, 100,
msg.arg1, false);
mNotification.contentView.setTextViewText(R.id.progress, "下载"
+ msg.arg1 + "%");
mNotificationManager.notify(NOTIFY_ID, mNotification);
break;
case DOWN_COMPLETE:
removeMessages(DOWN_LOADING);
Toast.makeText(mContext, "下载完成", Toast.LENGTH_SHORT).show();
mDownUtil.installApk(mContext, (File) msg.obj);
stopService();
break;
case DOWN_ERROR:
removeMessages(DOWN_LOADING);
Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
stopService();
break;
default:
break;
}
}

/**
* 如果无下载任务,关闭服务
*/
private void stopService() {
stopSelf(-1);
}

}
}


DownloadUtil:

public class DownloadUtil {
private int totalSize;
private int progress;
private File downFile = null;

public File downloadFile(String downUrl)
{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
try
{
URL url = new URL(downUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(1000 * 5);
totalSize = conn.getContentLength();
if (totalSize <= 0)
{
return null;
}
progress = 0;
InputStream is = conn.getInputStream();
String filename = downUrl.substring(downUrl.lastIndexOf("/") + 1);
downFile = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos = new FileOutputStream(downFile);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1)
{
fos.write(buffer, 0, len);
progress += len;
}
fos.flush();
fos.close();
bis.close();
is.close();
conn.disconnect();
}
catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
return downFile;
}

public void installApk(Context mContext, File apkFile)
{
if (!apkFile.exists())
{
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(i);
}

public void setOnDownloadListener(IOnDownloadListener listener)
{
listener.updateNotification(progress, totalSize, downFile);
}

public interface IOnDownloadListener
{
public void updateNotification(int progress, int totalSize, File downFile);
}
}


download_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="@drawable/ic_launcher"
android:scaleType="fitXY"
android:contentDescription="@string/action_settings" />

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_weight="1" />

<TextView
android:id="@+id/progress"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_marginRight="5dp"
android:text="" />

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: