我有一个应用要从一个很旧的版本更新为Android Pie。当用户按下侧键时,它会响应电话铃声音量的变化。我的代码如下。我的targetSdkVersion是28
我有两个硬件设备。在棉花糖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");
}
}
}
答案 0 :(得分:0)
I found that in some devices, you didn't receive volume_ring
or volume_music
changes in ContentObserver
. You need to use a broadcast receiver with intentFilter RINGER_MODE_CHANGED_ACTION
. I think pixel uses this broadcast receiver also.RINGER_MODE_CHANGED_ACTION
is used to identify the modes of volume like silent, loud etc also.
refer this link also