0

我有一个应用程序,我正在从一个非常旧的版本更新到 Android Pie。当用户按下侧键时,它会响应电话铃声音量的变化。我的代码如下。我的 targetSdkVersion 是 28

我有两个硬件设备。在 Marshmallow Galaxy S3 上,一切正常,但在 Pie Pixel 2 设备上,有时在我更改铃声音量和我的内容观察者收到 onChange 调用之间会有很长的延迟。将铃声从打开切换到关闭时,延迟通常约为 5 秒,但有时可能为 30 秒或更长。通常从响铃关闭到响铃打开,速度更快。

什么可以解释这一点?

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");
        }
    }
}
4

1 回答 1

0

我发现在某些设备中,您没有收到volume_ringvolume_music更改ContentObserver. 您需要使用带有 intentFilter 的广播接收器RINGER_MODE_CHANGED_ACTION。我认为像素也使用这个广播接收器。RINGER_MODE_CHANGED_ACTION用于识别音量模式,如静音、响亮等。

也参考这个链接

于 2018-12-03T13:05:40.897 回答