Progress bar in notification android studio example
Hello Guys. Welcome to our new tutorial of the Progress bar in notification using android studio. notification progress is used to display the progress in the notification bar. In this android tutorial, we are going to learn about how to get a notification progress bar. please follow the code given below to display the notification progress bar in android.
- First Create a new project in Android Studio
- File ⇒ New Android ⇒ Application Project
- Then Open src -> package -> MainActivity.java and then add following code :
Add the following code to src/MainActivity.java
JAVA (MainActivity.java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import android.app.NotificationManager; import android.content.Context; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class ProgressNotification extends AppCompatActivity { private NotificationManager noti; private NotificationCompat.Builder build; int id = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_progress_notification); Button b1 = (Button) findViewById(R.id.btnShow); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { noti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); build = new NotificationCompat.Builder(ProgressNotification.this); build.setContentTitle("File Download") .setContentText("Download in progress") .setSmallIcon(R.drawable.ic_launcher_background); new Thread( new Runnable() { @Override public void run() { int incr; for (incr = 0; incr <= 100; incr+=5) { build.setProgress(100, incr, false); noti.notify(id, build.build()); try { Thread.sleep(1*1000); } catch (InterruptedException e) { Log.d("TAG", "sleep failure"); } } build.setContentText("Download completed") .setProgress(0,0,false); noti.notify(id, build.build()); } } ).start(); } }); } } |
Now open res -> layout -> activity_main.xml file and just implement the following XML code .
XML (activity_main.xml)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/btnShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Notification" android:layout_marginTop="100dp" android:layout_marginLeft="120dp"/> </LinearLayout> |