Java 如何使用RemoteView在所有android平台的通知中显示progressbar
我想在所有android平台的通知中显示Java 如何使用RemoteView在所有android平台的通知中显示progressbar,java,android,Java,Android,我想在所有android平台的通知中显示progressbar。我使用远程视图在android中显示progressbar。我已经在我的项目中添加了android-support-v4库。如果我替换 mBuilder = new NotificationCompat.Builder(MainActivity.this); notification = mBuilder.build(); 至 notification = new Notification(R.drawable.notifi
progressbar
。我使用远程视图在android中显示progressbar
。我已经在我的项目中添加了android-support-v4库。如果我替换
mBuilder = new NotificationCompat.Builder(MainActivity.this);
notification = mBuilder.build();
至
notification = new Notification(R.drawable.notification, "simulating a upload", System .currentTimeMillis());
然后显示通知,但它是不推荐使用的方法
下面是代码:
class SendDatabaseToServer extends
AsyncTask<ArrayList<LogFishMetadata>, Integer, String> {
private NotificationCompat.Builder mBuilder;
private NotificationManager mNotifyManager;
private RemoteViews remoteViews;
private Intent intent;
private PendingIntent pendingIntent;
private Notification notification;
private int notificationId = 1;
int start;
int percentage;
int inc;
public SendDatabaseToServer(int value) {
// TODO Auto-generated constructor stub
logout = value;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
intent = new Intent(MainActivity.this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(MainActivity.this,
notificationId, intent, 0);
remoteViews = new RemoteViews(getPackageName(),
R.layout.notification_downloader);
mBuilder = new NotificationCompat.Builder(MainActivity.this);
notification = mBuilder.build();
//notification = new Notification(R.drawable.notification, "simulating a upload", System.currentTimeMillis());
notification.contentIntent = pendingIntent;
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.contentView = remoteViews;
notification.contentView.setTextViewText(R.id.timeStamp, DateTime.getStringFromDate(new Date()));
notification.contentView.setTextViewText(R.id.progress,
"UPloading....");
notification.contentView.setProgressBar(R.id.progressBar, 100, 0,
false);
mNotifyManager.notify(notificationId, notification);
}
@Override
protected String doInBackground(ArrayList<LogFishMetadata>... params) {
// TODO Auto-generated method stub
int count = params[0].size();
percentage=100/count;
for (int i = 0; i < params[0].size(); i++) {
System.out.println("........." + i);
start=i*percentage;
inc=i+1;
try {
database.updateServerdata(params[0].get(i));
for(int j=start;j<=inc*percentage;j++)
{
publishProgress(j);
}
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// progressBar.setProgress(values[0]);
System.out.println("values......." + values[0]);
if(values[0]>=100)
{
values[0]=98;
}
notification.contentView.setProgressBar(R.id.progressBar, 100,
values[0], false);
mNotifyManager.notify(notificationId, notification);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
notification.contentView.setTextViewText(R.id.progress,
"UPloading Complete");
notification.contentView.setProgressBar(R.id.progressBar,100, 100,
false);
mNotifyManager.notify(notificationId, notification);
if (logout == 2) {
System.out.println(" send Aler dialog....................................");
logoutConfirmationDialog("Sync Complete; Do you still want to logout?");
}
System.out.println("complete");
}
}
public class DownloadTask extends AsyncTask<String, Integer, Void> {
private NotificationHelper mNotificationHelper;
public static int notificationID = 1;
SharedPreferences settings;
SharedPreferences.Editor editor;
Context context;
String title;
public static String downlaodPath;
boolean download = false;
public DownloadTask(Context context, String title) {
this.context = context;
this.title = title;
mNotificationHelper = new NotificationHelper(context, title);
}
protected void onPreExecute() {
notificationID++;
mNotificationHelper.createNotification(notificationID);
}
@Override
protected Void doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
downlaodPath = "mnt/sdcard/Demo/"+title + ".mp3";
File file = new File("mnt/sdcard/Demo/");
file.mkdirs();
File outputfile = new File(file, title + ".mp3");
FileOutputStream fileOutput = new FileOutputStream(outputfile);
InputStream inputStream = conexion.getInputStream();
int totalSize = conexion.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) != -1) {
downloadedSize += bufferLength;
onProgressUpdate((int) ((downloadedSize * 100) / totalSize));
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e) {
download = true;
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mNotificationHelper.progressUpdate(progress[0]);
}
protected void onPostExecute(Void result) {
if (download) {
Toast.makeText(context, "Could Not Connect to Server.", 5).show();
mNotificationHelper.clearNotification();
}
else
mNotificationHelper.completed();
}
}
public class NotificationHelper extends Activity {
private Context mContext;
private int NOTIFICATION_ID = 1;
private Notification mNotification;
private NotificationManager mNotificationManager;
private PendingIntent mContentIntent;
private CharSequence mContentTitle;
private String title;
CharSequence tickerText;
int icon;
public NotificationHelper(Context context, String title) {
mContext = context;
this.title = title;
}
public void createNotification(int newtask) {
mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
NOTIFICATION_ID = newtask;
icon = android.R.drawable.stat_sys_download;
tickerText = mContext.getString(R.string.download);
long when = System.currentTimeMillis();
mNotification = new Notification(icon, tickerText, when);
mContentTitle = title;
CharSequence contentText = "0% complete";
Intent notificationIntent = new Intent();
mContentIntent = PendingIntent.getActivity(mContext, 0,
notificationIntent, 0);
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);
mNotification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
public void progressUpdate(int percentageComplete) {
CharSequence contentText = percentageComplete + "% complete";
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
public void completed() {
mNotificationManager.cancel(NOTIFICATION_ID);
Notification completeNotification = new Notification(icon, tickerText,
System.currentTimeMillis());
try {
PackageManager packageManager = mContext.getPackageManager();
Intent completeIntent = new Intent();
PendingIntent cIntent = PendingIntent.getActivity(mContext, 0,
completeIntent, 0);
completeNotification.setLatestEventInfo(mContext, title,
"Download Complete", cIntent);
completeNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(NOTIFICATION_ID, completeNotification);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Log.e("LOG", "last");
TestFragment3.activity.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
public void clearNotification() {
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
类SendDatabaseToServer扩展
异步任务{
私人通知建筑商;
私人通知经理通知经理;
私有远程视图远程视图;
私人意图;
私人吊挂帐篷;
私人通知;
私有int notificationId=1;
int启动;
整数百分比;
国际公司;
公共SendDatabaseToServer(int值){
//TODO自动生成的构造函数存根
注销=值;
}
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
mNotifyManager=(NotificationManager)getSystemService(Context.NOTIFICATION\u服务);
意图=新意图(MainActivity.this、MainActivity.class);
PendingEvent=PendingEvent.getActivity(MainActivity.this,
notificationId,intent,0);
RemoteView=新的RemoteView(getPackageName(),
R.布局通知(下载程序);
mBuilder=新通知compat.Builder(MainActivity.this);
通知=mBuilder.build();
//通知=新通知(R.drawable.notification,“模拟上载”,System.currentTimeMillis());
notification.contentIntent=pendingent;
notification.flags=notification.flags
|Notification.FLAG_持续事件;
notification.contentView=远程视图;
notification.contentView.setTextViewText(R.id.timeStamp,DateTime.getStringFromDate(new Date());
notification.contentView.setTextViewText(R.id.progress,
“上传…”;
notification.contentView.setProgressBar(R.id.progressBar,100,0,
假);
mNotifyManager.notify(notificationId,notification);
}
@凌驾
受保护的字符串doInBackground(ArrayList…params){
//TODO自动生成的方法存根
int count=params[0]。大小();
百分比=100/计数;
对于(int i=0;i
您应该将兼容性库添加到您的项目中。您可以使用Android工具|添加支持库
来完成此操作。然后您将使用该库中的通知兼容性
,它有生成器
我在我的一个项目中使用了以下代码希望这对您有所帮助:
下载任务类:
class SendDatabaseToServer extends
AsyncTask<ArrayList<LogFishMetadata>, Integer, String> {
private NotificationCompat.Builder mBuilder;
private NotificationManager mNotifyManager;
private RemoteViews remoteViews;
private Intent intent;
private PendingIntent pendingIntent;
private Notification notification;
private int notificationId = 1;
int start;
int percentage;
int inc;
public SendDatabaseToServer(int value) {
// TODO Auto-generated constructor stub
logout = value;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
intent = new Intent(MainActivity.this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(MainActivity.this,
notificationId, intent, 0);
remoteViews = new RemoteViews(getPackageName(),
R.layout.notification_downloader);
mBuilder = new NotificationCompat.Builder(MainActivity.this);
notification = mBuilder.build();
//notification = new Notification(R.drawable.notification, "simulating a upload", System.currentTimeMillis());
notification.contentIntent = pendingIntent;
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.contentView = remoteViews;
notification.contentView.setTextViewText(R.id.timeStamp, DateTime.getStringFromDate(new Date()));
notification.contentView.setTextViewText(R.id.progress,
"UPloading....");
notification.contentView.setProgressBar(R.id.progressBar, 100, 0,
false);
mNotifyManager.notify(notificationId, notification);
}
@Override
protected String doInBackground(ArrayList<LogFishMetadata>... params) {
// TODO Auto-generated method stub
int count = params[0].size();
percentage=100/count;
for (int i = 0; i < params[0].size(); i++) {
System.out.println("........." + i);
start=i*percentage;
inc=i+1;
try {
database.updateServerdata(params[0].get(i));
for(int j=start;j<=inc*percentage;j++)
{
publishProgress(j);
}
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// progressBar.setProgress(values[0]);
System.out.println("values......." + values[0]);
if(values[0]>=100)
{
values[0]=98;
}
notification.contentView.setProgressBar(R.id.progressBar, 100,
values[0], false);
mNotifyManager.notify(notificationId, notification);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
notification.contentView.setTextViewText(R.id.progress,
"UPloading Complete");
notification.contentView.setProgressBar(R.id.progressBar,100, 100,
false);
mNotifyManager.notify(notificationId, notification);
if (logout == 2) {
System.out.println(" send Aler dialog....................................");
logoutConfirmationDialog("Sync Complete; Do you still want to logout?");
}
System.out.println("complete");
}
}
public class DownloadTask extends AsyncTask<String, Integer, Void> {
private NotificationHelper mNotificationHelper;
public static int notificationID = 1;
SharedPreferences settings;
SharedPreferences.Editor editor;
Context context;
String title;
public static String downlaodPath;
boolean download = false;
public DownloadTask(Context context, String title) {
this.context = context;
this.title = title;
mNotificationHelper = new NotificationHelper(context, title);
}
protected void onPreExecute() {
notificationID++;
mNotificationHelper.createNotification(notificationID);
}
@Override
protected Void doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
downlaodPath = "mnt/sdcard/Demo/"+title + ".mp3";
File file = new File("mnt/sdcard/Demo/");
file.mkdirs();
File outputfile = new File(file, title + ".mp3");
FileOutputStream fileOutput = new FileOutputStream(outputfile);
InputStream inputStream = conexion.getInputStream();
int totalSize = conexion.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) != -1) {
downloadedSize += bufferLength;
onProgressUpdate((int) ((downloadedSize * 100) / totalSize));
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e) {
download = true;
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mNotificationHelper.progressUpdate(progress[0]);
}
protected void onPostExecute(Void result) {
if (download) {
Toast.makeText(context, "Could Not Connect to Server.", 5).show();
mNotificationHelper.clearNotification();
}
else
mNotificationHelper.completed();
}
}
public class NotificationHelper extends Activity {
private Context mContext;
private int NOTIFICATION_ID = 1;
private Notification mNotification;
private NotificationManager mNotificationManager;
private PendingIntent mContentIntent;
private CharSequence mContentTitle;
private String title;
CharSequence tickerText;
int icon;
public NotificationHelper(Context context, String title) {
mContext = context;
this.title = title;
}
public void createNotification(int newtask) {
mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
NOTIFICATION_ID = newtask;
icon = android.R.drawable.stat_sys_download;
tickerText = mContext.getString(R.string.download);
long when = System.currentTimeMillis();
mNotification = new Notification(icon, tickerText, when);
mContentTitle = title;
CharSequence contentText = "0% complete";
Intent notificationIntent = new Intent();
mContentIntent = PendingIntent.getActivity(mContext, 0,
notificationIntent, 0);
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);
mNotification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
public void progressUpdate(int percentageComplete) {
CharSequence contentText = percentageComplete + "% complete";
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
public void completed() {
mNotificationManager.cancel(NOTIFICATION_ID);
Notification completeNotification = new Notification(icon, tickerText,
System.currentTimeMillis());
try {
PackageManager packageManager = mContext.getPackageManager();
Intent completeIntent = new Intent();
PendingIntent cIntent = PendingIntent.getActivity(mContext, 0,
completeIntent, 0);
completeNotification.setLatestEventInfo(mContext, title,
"Download Complete", cIntent);
completeNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(NOTIFICATION_ID, completeNotification);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Log.e("LOG", "last");
TestFragment3.activity.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
public void clearNotification() {
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
我在我的项目中添加了andoid-support-v4。还有其他库添加了吗?建议。我已经导入了android.support.v4.app.NotificationCompat;然后我使用私有的android.support.v4.app.NotificationCompat.Builder mBuilder;mBuilder=new NotificationCompat.Builder(此);mBuilder.setSmallIcon etcNotificationHelper不是android中的一个类。我从哪里得到它?如果link是这个,那么还有一个去擦亮的方法。setLatestEventInfo(mContext,mContentTitle,contentText,mContentIntent)&mNotification=新通知(icon,tickerText,when);;