Sometime we need to download large file from server or some progress which takes time. For user experience we show progress bar so that user can check estimate time and progress completion.
This blog is about how to set up Progress bar in Notification like download manager.
Here we go.
1. Create Android project in Android Studio.
2. Create Activity with name "ProgressActivity".
3. Create xml like below.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.basicnotifications.ProgressActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Notification demo for progressbar notification. click on Button to show Progressbar notification on notification bar."
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="131dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fixed-duration progress"
android:onClick="showNotification"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
4. Create shoNotification() in java class.
public void showNotification(View view) {
}
5. Create NotificationManager and Builder instance.
mNotifyManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
6. Set Content Title,Content text and small icon.
mBuilder.setContentTitle("Downloading File")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_launcher);
7. Create different Thread to setup ProgressBar work for notification.
8. Write below code.
new Thread(
new Runnable() {
@Override
public void run() {
int incr;
for (incr = 0; incr <= 100; incr+=5) {
mBuilder.setProgress(100, incr, false);
mNotifyManager.notify(11, mBuilder.build());
try {
// Sleep for 3 seconds
Thread.sleep(3*1000);
} catch (InterruptedException e) {
}
}
// When the loop is finished, updates the notification
mBuilder.setContentText("Download complete")
.setProgress(0,0,false);
mNotifyManager.notify(11, mBuilder.build());
}
}
// Starts the thread by calling the run() method in its Runnable
).start();
9. To display an indeterminate activity indicator replace below line.
mBuilder.setProgress(100, incr, false);
with
mBuilder.setProgress(0, 0, true);
Happy coding :D
0 Comment(s)