0

I want to update notification from another activity and I declare it on the service class, I make log also a log is print mean method call but can't update notification progress bar value.

MyNotyficationService class below and my notification code write in this class.


public class MyNotyficationService extends Service {
    public static final String NOTIFICATION_CHANNEL_ID = "channelForground";
    public static final String NOTIFICATION_CHANNEL_NAME = "com.example.notificationdemo";
    NotificationCompat.Builder notification;
    NotificationChannel notificationChannel;
    NotificationManager manager;
    RemoteViews contentView;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        contentView = new RemoteViews("com.example.android", R.layout.notification_layout_custom);

        showNotification("0");

        return START_NOT_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    public void updateNoty(int per){
        Log.d("CALL__m","call" +per);
        contentView.setTextViewText(R.id.battery_level_Status, "Downloading : " + per + "%");
        contentView.setProgressBar(R.id.progressBar_notification_current_battery_level, 100, per, false);
        manager.notify(42, notification.build());
    }

    public void showNotification(String body) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            if (manager != null) {
                manager.createNotificationChannel(notificationChannel);
            }
        }

        contentView.setTextViewText(R.id.battery_level_Status, "Downloading : " + body + "%");
        contentView.setProgressBar(R.id.progressBar_notification_current_battery_level, 100, Integer.parseInt(body), false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new NotificationCompat.Builder(getApplicationContext())
                    .setChannelId(NOTIFICATION_CHANNEL_ID)
                    .setOngoing(true)
                    .setOnlyAlertOnce(true)
                    .setSmallIcon(R.drawable.cat_drinking)
                    .setContent(contentView);
        } else {
            notification = new NotificationCompat.Builder(getApplicationContext())
                    .setOngoing(true)
                    .setOnlyAlertOnce(true)
                    .setContent(contentView)
                    .setSmallIcon(R.drawable.cat_drinking);
        }
        startForeground(10, notification.build());
    }
    private void startService_() {
        Intent restartService = new Intent(getApplicationContext(), MyNotyficationService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(restartService);
        } else {
            startService(restartService);
        }
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 1000, restartServicePI);
    }


    @Override
    public void onTaskRemoved(Intent rootIntent) {
        startService_();
    }
}

And I want to update notification progress from another activity class, so what I do for that?


public class HomeActivity extends AppCompatActivity {

  public MyNotyficationService myNotyficationService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_screen_image);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Intent serviceIntent = new Intent(HomeActivity.this, ForegroundService.class);
                ContextCompat.startForegroundService(HomeActivity.this, serviceIntent);
            } else {
                startService(new Intent(HomeActivity.this, ForegroundService.class));
            }

        myNotyficationService= new MyNotyficationService();
        myNotyficationService.updateNoty(50);
   }

In my service class, I declare below method and I got log value but can't update notification progress

 public void updateNoty(int per){
        Log.d("CALL__m","call" +per);
        contentView.setTextViewText(R.id.battery_level_Status, "Downloading : " + per + "%");
        contentView.setProgressBar(R.id.progressBar_notification_current_battery_level, 100, per, false);
        manager.notify(42, notification.build());
    }

if anyone has another solution for that then share your answer

My Custom ContentView is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="15dp"
    android:paddingTop="10dp"
    android:paddingRight="15dp"
    android:paddingBottom="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/notification_image_icon"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/txt_notification_heading"
            android:layout_width="wrap_content"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/notification_image_icon"
            android:text="@string/app_name"
            android:textColor="#323232" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/battery_level_Status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/notification_image_icon"
            android:text="50%"
            android:textColor="#323232" />

    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar_notification_current_battery_level"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginTop="5dp"
        android:indeterminate="false"
        android:max="100"
        android:progress="50"
        android:progressDrawable="@drawable/notificationprogress" />
</LinearLayout>

My manifest for service class init

<service
            android:name=".Acivity.ForegroundService"
            android:enabled="true"
            android:exported="true"></service>
13
  • are you using contentView custom?
    – haresh
    Jan 3, 2020 at 6:03
  • 1
    @PrafulKorat where do you init myNotyficationService?
    – Son Truong
    Jan 3, 2020 at 6:50
  • 1
    @PrafulKorat I mean where do you init myNotyficationService variable in HomeActivity. Because from your code, this line myNotyficationService.updateNoty(50); will make your app crash.
    – Son Truong
    Jan 3, 2020 at 7:07
  • 1
    @PrafulKorat In Android you cannot create a service like myNotyficationService= new MyNotyficationService();, and call methods on it. First, you need to register the service with Android system, second call startService() or startForegroundService(), then Android will create and start the service for you. If you want to update status of progress bar, then you can send broadcast from your activity to service, then service will update the progress.
    – Son Truong
    Jan 3, 2020 at 7:19
  • 1
    @PrafulKorat as I said, you cannot create an instance of Service, in this case you should send a broadcast to your service instead of creating a service and call updateNotify() method on it.
    – Son Truong
    Jan 3, 2020 at 7:34

1 Answer 1

1

This is what i am doing to update notification from service but i am using NotificationCompat.Builder object to set progress and text.

  private void raiseNotification(NotificationCompat.Builder b, int counter) {
    b.setContentText("Downloaded " + counter + "% ");
    b.setProgress(100, counter, false);
    b.setOngoing(true);
    if (counter > 99) {
        b.setAutoCancel(true);
        b.setOngoing(false);
        b.setContentTitle("Download complete").setProgress(0, 0, false);
    }
    if (mgr != null) mgr.notify(NOTIFICATION_ID, b.build());
}
2
  • Sure what i am telling you that when you set text through NotificationCompat.Builder b it working in my case so is that not working in your case?
    – haresh
    Jan 3, 2020 at 6:59
  • @PrafulKorat ok let me create demo with your code will let you know
    – haresh
    Jan 3, 2020 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.