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>
Praful Korat
  • 374
  • 4
  • 22
  • are you using contentView custom? – haresh Jan 03 '20 at 06:03
  • Yes, I added my content view in question. – Praful Korat Jan 03 '20 at 06:05
  • `DownloadManager` provides such a progress bar ... – Martin Zeitler Jan 03 '20 at 06:07
  • 1
    @PrafulKorat where do you init `myNotyficationService`? – Son Truong Jan 03 '20 at 06:50
  • @Nhất Giang in menifest, i added in que now – Praful Korat Jan 03 '20 at 06:59
  • 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 03 '20 at 07:07
  • yes in above i use `myNotyficationService.updateNoty(50);` ,i added it – Praful Korat Jan 03 '20 at 07:14
  • 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 03 '20 at 07:19
  • Yes , i also call that method but i forgot write into code.check now. – Praful Korat Jan 03 '20 at 07:29
  • try adding post delayed on ui thread, you ui thread must be busy so add update action in the queue xd – silentsudo Jan 03 '20 at 07:31
  • 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 03 '20 at 07:34
  • An example of a code sample for it? then share link or code – Praful Korat Jan 03 '20 at 08:34
  • use Messenger to send data form activty to running serivce. for ref see this link https://stackoverflow.com/questions/43736714/how-to-pass-data-from-activity-to-running-service#answer-43737298 – Lingeshwaran Jan 04 '20 at 10:37

1 Answers1

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());
}
haresh
  • 1,424
  • 2
  • 12
  • 18
  • 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 03 '20 at 06:59
  • @PrafulKorat ok let me create demo with your code will let you know – haresh Jan 03 '20 at 07:14