John
John

Reputation: 74

Android displaying progress in a Notification

here is my code :

public class MainActivity extends Activity {

private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this);
}


public void click(View view) {
    noti();
}


private void noti() {
    mBuilder.setContentTitle("Picture Download")
        .setContentText("Download in progress")
        .setSmallIcon(R.drawable.ic_launcher);
    // Start a lengthy operation in a background thread
    new Thread(
        new Runnable() {
            @Override
            public void run() {
                int incr;
                // Do the "lengthy" operation 20 times
                for (incr = 0; incr <= 100; incr+=5) {
                        // Sets the progress indicator to a max value, the
                        // current completion percentage, and "determinate"
                        // state
                        mBuilder.setProgress(100, incr, false);
                        // Displays the progress bar for the first time.
                        mNotifyManager.notify(0, mBuilder.build());
                            // Sleeps the thread, simulating an operation
                            // that takes time
                            try {
                                // Sleep for 5 seconds
                                Thread.sleep(1*1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                }
                // When the loop is finished, updates the notification
                mBuilder.setContentText("Download complete")
                // Removes the progress bar
                        .setProgress(0,0,false);
                mNotifyManager.notify(0, mBuilder.build());
            }
        }
    // Starts the thread by calling the run() method in its Runnable
    ).start();
}

}

it works fine on android 4.2.2 device , but when I tried to run it on an android 2.2 device , the notification didn't show up,and I got the following logs:

RuntimeException  in notify -
java.lang.Throwable: stack dump
at android.app.NotificationManager.notify(NotificationManager.java:118)
at android.app.NotificationManager.notify(NotificationManager.java:92)
at com.gyh.notitest.MainActivity$1.run(MainActivity.java:49)
at java.lang.Thread.run(Thread.java:1019)

can anyone help me ? how can I display a progress bar in a Notification on android 2.2 devices without custom layout?

thanks!

Upvotes: 0

Views: 7935

Answers (3)

EdgeDev
EdgeDev

Reputation: 2486

I re-wrote your code to enable multiple Notification Progress. Also updated to work on android Oreo+

class MainActivity : AppCompatActivity(){
    private var mNotifyManager: NotificationManagerCompat? = null
    private var mBuilder: NotificationCompat.Builder? = null
    private var notificationId = 0
    val CHANNEL_ID ="download_progress_notification"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mNotifyManager = NotificationManagerCompat.from(this)
        mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
    }
    private fun noti(notficationId : Int) {
        mBuilder?.setContentTitle("Picture Download")
                ?.setContentText("Download in progress")
                ?.setSmallIcon(R.mipmap.ic_launcher)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
            val name = "my channel2"
            val description = "channel description2"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description)
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }

        // Start a lengthy operation in a background thread
        Thread(object : Runnable{
            override fun run() {
                var incr: Int
                // Do the "lengthy" operation 20 times
                incr = 0
                while (incr <= 100) {
                    // Sets the progress indicator to a max value, the
                    // current completion percentage, and "determinate"
                    // state
                    mBuilder?.setProgress(100, incr, false)
                    // Displays the progress bar for the first time.
                    mNotifyManager?.notify(notficationId, mBuilder!!.build())
                    // Sleeps the thread, simulating an operation
                    // that takes time
                    try {
                        // Sleep for 5 seconds
                        Thread.sleep((1 * 1000).toLong())
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                    incr += 5
                }
                // When the loop is finished, updates the notification
                mBuilder?.setContentText("Download complete")
                        // Removes the progress bar
                        ?.setProgress(0, 0, false)
                mNotifyManager?.notify(notficationId, mBuilder!!.build())
            }
        }).start()
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.menu_option -> {
                noti(notificationId++)
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}

Upvotes: 0

John
John

Reputation: 74

Never mind..

I change my code to:

public class MainActivity extends Activity {

private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent resultIntent = new Intent(this, MainActivity.class);
    PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
        this,
        0,
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    );


    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(
            getApplicationContext()).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setContentIntent(resultPendingIntent);
}


public void click(View view) {
    noti();
}


private void noti() {
    // Start a lengthy operation in a background thread
    new Thread(
        new Runnable() {
            @Override
            public void run() {
                int incr;
                // Do the "lengthy" operation 20 times
                for (incr = 0; incr <= 100; incr+=5) {
                        // Sets the progress indicator to a max value, the
                        // current completion percentage, and "determinate"
                        // state
                        mBuilder.setProgress(100, incr, false);
                        // Displays the progress bar for the first time.
                        mNotifyManager.notify(0, mBuilder.build());
                            // Sleeps the thread, simulating an operation
                            // that takes time
                            try {
                                // Sleep for 5 seconds
                                Thread.sleep(1*1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                }
                // When the loop is finished, updates the notification
                mBuilder.setContentText("Download complete")
                // Removes the progress bar
                        .setProgress(0,0,false);
                mNotifyManager.notify(0, mBuilder.build());
            }
        }
    // Starts the thread by calling the run() method in its Runnable
    ).start();
}

}

Then there came the Notification , But no progress T_T There is nothing I can do about it .. the only way I can think of right now is a custom layout with a progress bar...

Upvotes: 2

Long Dao
Long Dao

Reputation: 1371

Have you tried import the v4.jar library to your project? It supports features of new api version running on low api ( Android 2.2 for instance).

Cheers,

Upvotes: 1

Related Questions