I have an app that I'm updating from a very old version to Android Pie. It responds to changes in phone ringer volume when the user presses the side key. My code is below. My targetSdkVersion is 28
I've got two hardware devices. On the Marshmallow Galaxy S3, everything works fine, but on the Pie Pixel 2 device, sometimes there's a very long delay between the time I change ringer volume, and when my content observer receives the onChange call. When switching the ringer from on to off, the delay is typically about 5 seconds, but at times it can be 30 seconds or more. Generally going from ringer off to ringer on, is speedier.
What could account for this?
public class VolumeService extends Service
{
private VolumeService.VolumeContentObserver observer = null;
private static Notification notification = null;
private static int notificationID = 1;
@Override
public void onCreate()
{
super.onCreate();
observer = new VolumeService.VolumeContentObserver( this );
Intent mainIntent = new Intent( this, MainActivity.class );
mainIntent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK );
Notification.Builder builder = new Notification.Builder( this )
.setContentTitle( getString( R.string.notification_title ) )
.setContentText( getString( R.string.notification_text ) )
.setSmallIcon( R.drawable.ic_audio_vol )
.setContentIntent( PendingIntent.getActivity( this, 0, mainIntent, 0 ) );
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O )
builder.setChannelId( getString( R.string.channel_id ) );
notification = builder.build();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
observer.register();
startForeground( notificationID, notification );
return START_STICKY;
}
@Override
public IBinder onBind( Intent intent )
{
return null;
}
private class VolumeContentObserver extends ContentObserver
{
private Context context = null;
VolumeContentObserver( Context context )
{
super( new Handler() );
this.context = context;
}
void register()
{
context.getApplicationContext().getContentResolver()
.registerContentObserver( android.provider.Settings.System.CONTENT_URI, true, this );
}
@Override
public void onChange(boolean selfChange)
{
super.onChange( selfChange );
Log.d("VolumeService", "volume changed");
}
}
}