如何在下载的同时往Notification添加一个进度条。
并且Notification是可以添加多个的,并且点击那个进度条能返回到Activity里。以下是我写的下载的Activity,但是不知道如何实现同时在Notification添加一个进度条。
package com.pocketdigi.Notification;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;import org.apache.http.client.ClientProtocolException;import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;public class DownLoadFile extends Activity01
{
private ProgressBar pb;
private TextView tv;
private int fileSize;//文件大小
private int downLoadFileSize;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
pb=(ProgressBar)findViewById(R.id.down_pb);//Activity上的ProgressBar
tv=(TextView)findViewById(R.id.tv);//Activity上的Text
tv.setVisibility(View.GONE);//设这初始状态它们不显示
pb.setVisibility(View.GONE);
Button btDownLoad=(Button)findViewById(R.id.btDownLoad);
btDownLoad.setOnClickListener(btClick);
}
//单击下载按钮事件
OnClickListener btClick=new OnClickListener()
{
@Override
public void onClick(View v)
{
tv.setVisibility(View.VISIBLE);//显示
pb.setVisibility(View.VISIBLE);
new Thread(){
public void run(){
try {
down_file("http://img.yingyonghui.com/apk/113877/com.tencent.qq.1305527248382.apk","/sdcard/");
//下载文件,参数:第一个URL,第二个存放路径
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
};
private void down_file(String url,String path) throws IOException{
//下载函数
/*取得欲安装程序之文件名称*/
String fileEx = url.substring(url.lastIndexOf(".")+1,url.length()).toLowerCase();
String fileNa = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
//获取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
fileSize = conn.getContentLength();//根据响应获取文件大小
if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File myTempFile = File.createTempFile(fileNa, "."+fileEx);
FileOutputStream fos = new FileOutputStream(myTempFile);
//把数据存入路径+文件名
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0,myTempFile.getPath());
do
{
//循环读取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread; sendMsg(1,myTempFile.getPath());//更新进度条
} while (true); try
{
is.close();
} catch (Exception ex)
{
Log.e("tag", "error: " + ex.getMessage(), ex);
}
sendMsg(2,myTempFile.getPath());//通知下载完成
}
private void sendMsg(int flag,String filepath)
{
Message msg = new Message();
msg.what = flag;
Bundle bundle=new Bundle();
bundle.putString("filepath", filepath);
msg.setData(bundle);
handler1.sendMessage(msg);
}
private Handler handler1 = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted())
{
try
{
switch (msg.what)
{
case 0:
pb.setMax(fileSize);
case 1:
pb.setProgress(downLoadFileSize);
int result = downLoadFileSize * 100 / fileSize;
tv.setText("下载中:"+result + "%");
break;
case 2:
Toast.makeText(DownLoadFile.this, "文件下载完成", Toast.LENGTH_LONG).show();
pb.setVisibility(View.GONE);
tv.setVisibility(View.GONE);
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(DownLoadFile.this, error, 1).show();
break;
}
} catch (Exception e) {
Toast.makeText(DownLoadFile.this, e.toString(), 1).show();
}
}
super.handleMessage(msg);
}
};
}
download.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<ProgressBar android:id="@+id/down_pb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
style="?android:attr/progressBarStyleHorizontal"
/>
<Button android:id="@+id/btDownLoad"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="下载"
/>
</LinearLayout>在AndroidManifest.xml添加如下。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.INSTALL_PACKAGES"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>请各位前辈赐教!!
并且Notification是可以添加多个的,并且点击那个进度条能返回到Activity里。以下是我写的下载的Activity,但是不知道如何实现同时在Notification添加一个进度条。
package com.pocketdigi.Notification;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;import org.apache.http.client.ClientProtocolException;import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;public class DownLoadFile extends Activity01
{
private ProgressBar pb;
private TextView tv;
private int fileSize;//文件大小
private int downLoadFileSize;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
pb=(ProgressBar)findViewById(R.id.down_pb);//Activity上的ProgressBar
tv=(TextView)findViewById(R.id.tv);//Activity上的Text
tv.setVisibility(View.GONE);//设这初始状态它们不显示
pb.setVisibility(View.GONE);
Button btDownLoad=(Button)findViewById(R.id.btDownLoad);
btDownLoad.setOnClickListener(btClick);
}
//单击下载按钮事件
OnClickListener btClick=new OnClickListener()
{
@Override
public void onClick(View v)
{
tv.setVisibility(View.VISIBLE);//显示
pb.setVisibility(View.VISIBLE);
new Thread(){
public void run(){
try {
down_file("http://img.yingyonghui.com/apk/113877/com.tencent.qq.1305527248382.apk","/sdcard/");
//下载文件,参数:第一个URL,第二个存放路径
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
};
private void down_file(String url,String path) throws IOException{
//下载函数
/*取得欲安装程序之文件名称*/
String fileEx = url.substring(url.lastIndexOf(".")+1,url.length()).toLowerCase();
String fileNa = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
//获取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
fileSize = conn.getContentLength();//根据响应获取文件大小
if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File myTempFile = File.createTempFile(fileNa, "."+fileEx);
FileOutputStream fos = new FileOutputStream(myTempFile);
//把数据存入路径+文件名
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0,myTempFile.getPath());
do
{
//循环读取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread; sendMsg(1,myTempFile.getPath());//更新进度条
} while (true); try
{
is.close();
} catch (Exception ex)
{
Log.e("tag", "error: " + ex.getMessage(), ex);
}
sendMsg(2,myTempFile.getPath());//通知下载完成
}
private void sendMsg(int flag,String filepath)
{
Message msg = new Message();
msg.what = flag;
Bundle bundle=new Bundle();
bundle.putString("filepath", filepath);
msg.setData(bundle);
handler1.sendMessage(msg);
}
private Handler handler1 = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted())
{
try
{
switch (msg.what)
{
case 0:
pb.setMax(fileSize);
case 1:
pb.setProgress(downLoadFileSize);
int result = downLoadFileSize * 100 / fileSize;
tv.setText("下载中:"+result + "%");
break;
case 2:
Toast.makeText(DownLoadFile.this, "文件下载完成", Toast.LENGTH_LONG).show();
pb.setVisibility(View.GONE);
tv.setVisibility(View.GONE);
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(DownLoadFile.this, error, 1).show();
break;
}
} catch (Exception e) {
Toast.makeText(DownLoadFile.this, e.toString(), 1).show();
}
}
super.handleMessage(msg);
}
};
}
download.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<ProgressBar android:id="@+id/down_pb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
style="?android:attr/progressBarStyleHorizontal"
/>
<Button android:id="@+id/btDownLoad"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="下载"
/>
</LinearLayout>在AndroidManifest.xml添加如下。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.INSTALL_PACKAGES"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>请各位前辈赐教!!
tv.setVisibility(View.VISIBLE);//显示
pb.setVisibility(View.VISIBLE);我现在是不知道在Notification怎么显示进度条。我从网上找了很多帖子,要么能显示进度条,但是不能与我下载的进度条,同步!
package com.pocketdigi.Notification;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;import org.apache.http.client.ClientProtocolException;import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;public class DownLoadFile extends Activity {
private ProgressBar pb;
private TextView tv;
private int fileSize;//文件大小
private int downLoadFileSize;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
pb=(ProgressBar)findViewById(R.id.down_pb);//Activity上的ProgressBar
tv=(TextView)findViewById(R.id.tv);//Activity上的Text
tv.setVisibility(View.GONE);//设这初始状态它们不显示
pb.setVisibility(View.GONE);
Button btDownLoad=(Button)findViewById(R.id.btDownLoad);
btDownLoad.setOnClickListener(btClick);
}
//单击下载按钮事件
OnClickListener btClick=new OnClickListener()
{
@Override
public void onClick(View v)
{
tv.setVisibility(View.VISIBLE);//显示
pb.setVisibility(View.VISIBLE);
new Thread(){
public void run(){
try {
String url = "http://img.yingyonghui.com/apk/113877/com.tencent.qq.1305527248382.apk";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
down_file("http://img.yingyonghui.com/apk/113877/com.tencent.qq.1305527248382.apk","/sdcard/");
//下载文件,参数:第一个URL,第二个存放路径
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
};
private void down_file(String url,String path) throws IOException{
//下载函数
/*取得欲安装程序之文件名称*/
String fileEx = url.substring(url.lastIndexOf(".")+1,url.length()).toLowerCase();
String fileNa = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
//获取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
fileSize = conn.getContentLength();//根据响应获取文件大小
if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File myTempFile = File.createTempFile(fileNa, "."+fileEx);
FileOutputStream fos = new FileOutputStream(myTempFile);
//把数据存入路径+文件名
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0,myTempFile.getPath());
do
{
//循环读取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread; sendMsg(1,myTempFile.getPath());//更新进度条
} while (true); try
{
is.close();
} catch (Exception ex)
{
Log.e("tag", "error: " + ex.getMessage(), ex);
}
sendMsg(2,myTempFile.getPath());//通知下载完成
}
private void sendMsg(int flag,String filepath)
{
Message msg = new Message();
msg.what = flag;
Bundle bundle=new Bundle();
bundle.putString("filepath", filepath);
msg.setData(bundle);
handler1.sendMessage(msg);
}
private Handler handler1 = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted())
{
try
{
switch (msg.what)
{
case 0:
pb.setMax(fileSize);
case 1:
pb.setProgress(downLoadFileSize);
int result = downLoadFileSize * 100 / fileSize;
tv.setText("下载中:"+result + "%");
break;
case 2:
Toast.makeText(DownLoadFile.this, "文件下载完成", Toast.LENGTH_LONG).show();
pb.setVisibility(View.GONE);
pb.setVisibility(View.GONE);
tv.setVisibility(View.GONE);
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(DownLoadFile.this, error, 1).show();
break;
}
} catch (Exception e) {
Toast.makeText(DownLoadFile.this, e.toString(), 1).show();
}
}
super.handleMessage(msg);
}
};
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;import org.apache.http.client.ClientProtocolException;import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;public class DownLoadFile extends Activity {
private ProgressBar pb;
private TextView tv;
private int fileSize;//文件大小
private int downLoadFileSize;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
pb=(ProgressBar)findViewById(R.id.down_pb);//Activity上的ProgressBar
tv=(TextView)findViewById(R.id.tv);//Activity上的Text
tv.setVisibility(View.GONE);//设这初始状态它们不显示
pb.setVisibility(View.GONE);
Button btDownLoad=(Button)findViewById(R.id.btDownLoad);
btDownLoad.setOnClickListener(btClick);
}
//单击下载按钮事件
OnClickListener btClick=new OnClickListener()
{
@Override
public void onClick(View v)
{
tv.setVisibility(View.VISIBLE);//显示
pb.setVisibility(View.VISIBLE);
new Thread(){
public void run(){
try {
String url = "http://img.yingyonghui.com/apk/113877/com.tencent.qq.1305527248382.apk";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
};
}楼主用这段代码处理下,就不用每次下载2次了,每个下载任务都会在Statusbar的下拉view中显示出来,看看是否这种效果
package com.myAndroid.notification;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;import org.apache.http.client.ClientProtocolException;import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends Activity {
int result;
int notification_id=1;
NotificationManager nm;
Handler handler=new Handler();
Notification notification;
int count=0;
private ProgressBar pb;
private TextView tv;
private int fileSize;
private int downLoadFileSize;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt1=(Button)findViewById(R.id.bt1);
bt1.setOnClickListener(bt1lis);
pb=(ProgressBar)findViewById(R.id.down_pb);//Activity上的ProgressBar
tv=(TextView)findViewById(R.id.tv);//Activity上的Text
tv.setVisibility(View.GONE);//设这初始状态它们不显示
pb.setVisibility(View.GONE);
//建立notification
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification=new Notification(R.drawable.icon,"图标边的文字",System.currentTimeMillis());
notification.contentView = new RemoteViews(getPackageName(),R.layout.notification);
//使用notification.xml文件作VIEW
notification.contentView.setProgressBar(R.id.pb, 100,0, false);
//设置进度条,最大值 为100,当前值为0,最后一个参数为true时显示条纹
//(就是在Android Market下载软件,点击下载但还没获取到目标大小时的状态)
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.contentIntent = contentIntent;
}
OnClickListener bt1lis=new OnClickListener(){
@Override
public void onClick(View v)
{
tv.setVisibility(View.VISIBLE);//显示
pb.setVisibility(View.VISIBLE);
showNotification();//显示notification
//handler1.post(run);
new Thread(){
public void run(){
try {
down_file("http://img.yingyonghui.com/apk/9993/com.yingyonghui.et.1306217048680.apk","/sdcard/");
//下载文件,参数:第一个URL,第二个存放路径
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
};
private void down_file(String url,String path) throws IOException{
//下载函数
/*取得欲安装程序之文件名称*/
String fileEx = url.substring(url.lastIndexOf(".")+1,url.length()).toLowerCase();
String fileNa = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
//获取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
fileSize = conn.getContentLength();//根据响应获取文件大小
if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
File myTempFile = File.createTempFile(fileNa, "."+fileEx);
FileOutputStream fos = new FileOutputStream(myTempFile);
//把数据存入路径+文件名
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0,myTempFile.getPath());
int tmpNumread = 0;
do
{
//循环读取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
tmpNumread += numread;
downLoadFileSize += numread;
if (tmpNumread>20000) {//这里减少更新时间
sendMsg(1,myTempFile.getPath());//更新进度条
tmpNumread =0;
}
} while (true);
try
{
is.close();
} catch (Exception ex)
{
Log.e("tag", "error: " + ex.getMessage(), ex);
}
sendMsg(2,myTempFile.getPath());//通知下载完成
}
private void sendMsg(int flag,String filepath)
{
Message msg = new Message();
msg.what = flag;
Bundle bundle=new Bundle();
bundle.putString("filepath", filepath);
msg.setData(bundle);
handler1.sendMessage(msg);
}
private Handler handler1 = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted())
{
try
{
switch (msg.what)
{
case 0:
pb.setMax(fileSize);
case 1:
pb.setProgress(downLoadFileSize);
result = downLoadFileSize * 100 / fileSize;
tv.setText("下载中:"+result + "%");
notification.contentView.setProgressBar(R.id.pb, 100,result, false);
//设置当前值为count
showNotification();//这里是更新notification,就是更新进度条
break;
case 2:
pb.setVisibility(View.GONE);
tv.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "文件下载完成", 1).show();
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(MainActivity.this, error, 1).show();
break;
}
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), 1).show();
}
}
super.handleMessage(msg);
}
};
public void showNotification(){
nm.notify(notification_id, notification);
}
}
您看看经过同事改成这样!请各位前辈帮我看看有没有问题!我还没经过测试是否能在notification添加多个进度条!