Android 上传图片时通知栏中的进度条?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1871515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Progress bar in notification bar when uploading image?
提问by Mark
I'd like my app to upload an image to a web server. That part works.
我希望我的应用程序将图像上传到网络服务器。那部分工作。
I'm wondering if it's possible to somehow show the progress of the upload by entering an entry in the "notification bar". I see the Facebook app does this.
我想知道是否可以通过在“通知栏”中输入一个条目来以某种方式显示上传进度。我看到 Facebook 应用程序做到了这一点。
When you take a picture and choose to upload, the app lets you continue on, and somehow puts the picture upload notifications in a progress bar in the notification bar. I think that's pretty slick. I guess they spawn a new service or something to handle the upload and update that progress bar in the notification bar every so often.
当您拍照并选择上传时,该应用程序让您继续,并以某种方式将图片上传通知放在通知栏中的进度条中。我认为这很圆滑。我猜他们会产生一个新服务或其他东西来处理上传和更新通知栏中的进度条。
Thanks for any ideas
感谢您的任何想法
采纳答案by Eric Mill
回答by Paolo Rovelli
In Android, in order to display a progress bar in a Notification, you just need to initialize setProgress(...)into the Notification.Builder.
在 Android 中,为了在Notification 中显示进度条,您只需要将setProgress(...)初始化到Notification.Builder 中。
Note that, in your case, you would probably want to use even the setOngoing(true)flag.
请注意,在您的情况下,您甚至可能想要使用setOngoing(true)标志。
Integer notificationID = 100;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Set notification information:
Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext());
notificationBuilder.setOngoing(true)
.setContentTitle("Notification Content Title")
.setContentText("Notification Content Text")
.setProgress(100, 0, false);
//Send the notification:
Notification notification = notificationBuilder.build();
notificationManager.notify(notificationID, notification);
Then, your Service will have to notify the progress. Assuming that you store your (percentage) progress into an Integercalled progress(e.g. progress = 10):
然后,您的服务必须通知进度。假设您将(百分比)进度存储到一个名为progress的整数中(例如progress = 10):
//Update notification information:
notificationBuilder.setProgress(100, progress, false);
//Send the notification:
notification = notificationBuilder.build();
notificationManager.notify(notificationID, notification);
You can find more information on the API Notificationspage: http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress
您可以在API 通知页面上找到更多信息:http: //developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress
回答by Vivek Barai
You can try out this class it will help you to generate notification
你可以试试这个类它会帮助你生成通知
public class FileUploadNotification {
public static NotificationManager mNotificationManager;
static NotificationCompat.Builder builder;
static Context context;
static int NOTIFICATION_ID = 111;
static FileUploadNotification fileUploadNotification;
/*public static FileUploadNotification createInsance(Context context) {
if(fileUploadNotification == null)
fileUploadNotification = new FileUploadNotification(context);
return fileUploadNotification;
}*/
public FileUploadNotification(Context context) {
mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(context);
builder.setContentTitle("start uploading...")
.setContentText("file name")
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setProgress(100, 0, false)
.setAutoCancel(false);
}
public static void updateNotification(String percent, String fileName, String contentText) {
try {
builder.setContentText(contentText)
.setContentTitle(fileName)
//.setSmallIcon(android.R.drawable.stat_sys_download)
.setOngoing(true)
.setContentInfo(percent + "%")
.setProgress(100, Integer.parseInt(percent), false);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
if (Integer.parseInt(percent) == 100)
deleteNotification();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("Error...Notification.", e.getMessage() + ".....");
e.printStackTrace();
}
}
public static void failUploadNotification(/*int percentage, String fileName*/) {
Log.e("downloadsize", "failed notification...");
if (builder != null) {
/* if (percentage < 100) {*/
builder.setContentText("Uploading Failed")
//.setContentTitle(fileName)
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setOngoing(false);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
/*} else {
mNotificationManager.cancel(NOTIFICATION_ID);
builder = null;
}*/
} else {
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
public static void deleteNotification() {
mNotificationManager.cancel(NOTIFICATION_ID);
builder = null;
}
}
回答by CommonsWare
I'm not a Facebook user, so I do not know exactly what you're seeing.
我不是 Facebook 用户,所以我不知道你在看什么。
It is certainly possible to keep updating a Notification
, changing the icon to reflect completed progress. As you suspect, you would do this from a Service
with a background thread that is managing the upload.
当然可以不断更新 a Notification
,更改图标以反映已完成的进度。正如您所怀疑的那样,您可以Service
使用管理上传的后台线程来执行此操作。
回答by SumeetP
public class loadVideo extends AsyncTask<Void, Integer, Void> {
int progress = 0;
Notification notification;
NotificationManager notificationManager;
int id = 10;
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead;
int sentData = 0;
byte[] buffer;
String urlString = "http://xxxxx/xxx/xxxxxx.php";
try {
UUID uniqueKey = UUID.randomUUID();
fname = uniqueKey.toString();
Log.e("UNIQUE NAME", fname);
FileInputStream fileInputStream = new FileInputStream(new File(
selectedPath));
int length = fileInputStream.available();
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ fname + "" + lineEnd);
dos.writeBytes(lineEnd);
buffer = new byte[8192];
bytesRead = 0;
while ((bytesRead = fileInputStream.read(buffer)) > 0) {
dos.write(buffer, 0, bytesRead);
sentData += bytesRead;
int progress = (int) ((sentData / (float) length) * 100);
publishProgress(progress);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
Intent intent = new Intent();
final PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
notification = new Notification(R.drawable.video_upload,
"Uploading file", System.currentTimeMillis());
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.upload_progress_bar);
notification.contentIntent = pendingIntent;
notification.contentView.setImageViewResource(R.id.status_icon,
R.drawable.video_upload);
notification.contentView.setTextViewText(R.id.status_text,
"Uploading...");
notification.contentView.setProgressBar(R.id.progressBar1, 100,
progress[0], false);
getApplicationContext();
notificationManager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notification);
}
protected void onPostExecute(Void result) {
Notification notification = new Notification();
Intent intent1 = new Intent(MultiThreadActivity.this,
MultiThreadActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent1, 0);
int icon = R.drawable.check_16; // icon from resources
CharSequence tickerText = "Video Uploaded Successfully"; // ticker-text
CharSequence contentTitle = getResources().getString(
R.string.app_name); // expanded message
// title
CharSequence contentText = "Video Uploaded Successfully"; // expanded
// message
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application
// Context
notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, contentTitle, contentText,
pendingIntent);
String notificationService = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager) context
.getSystemService(notificationService);
notificationManager.notify(id, notification);
}
}
check this if it can help u
检查这个是否可以帮助你