在平常使用音乐播放器时经常会遇到锁屏会显示歌词功能,做的时候也是各种手机不适配,翻阅了网上的文章,发现都是好几年前的,适配的安卓版本比较低,所以我就整合了一下分享给大家.
例如下图:
主要用到的知识点
1.锁屏的广播监听
废话不多说,先上代码
广播接收的方法,用来接收自手机系统广播的开屏锁屏:
public class LockerReceiver extends BroadcastReceiver { private static final String TAG = "LockReceiver"; public LockerReceiver() { } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!TextUtils.isEmpty(action)) { if (action.equals(Intent.ACTION_POWER_CONNECTED)) { //todo } else if (action.equals(Intent.ACTION_SCREEN_ON)) { } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { Log.e(TAG, "onReceive---" + action); LockScreenActivity.startActivity(context); } } } }
注册一下该广播,可以在某个Activity,也可以在Application,也可以在Service,具体根据自己的业务需求来
private void registerLockerReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_POWER_CONNECTED); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); lockerReceiver = new LockerReceiver(); registerReceiver(lockerReceiver, filter); }
同时也需要在销毁方法里面反注册:
private void unregisterLockerReceiver() { if (lockerReceiver == null) { return; } unregisterReceiver(lockerReceiver); lockerReceiver = null; }
锁屏的Activity需要单独设置window的显示方式:
/** * 显示在锁屏上面 * @param window */ private void setLockerWindow(Window window) { WindowManager.LayoutParams lp = window.getAttributes(); if (Build.VERSION.SDK_INT > 18) { lp.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; } window.setAttributes(lp); window.getDecorView().setSystemUiVisibility(0x0); window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); }
开启该Activity时添加action标明为新的任务,并且要从任务栈中移出:
@NonNull private static Intent getIntent(Context context) { Intent screenIntent = new Intent(); screenIntent.setClass(context, LockScreenActivity.class); screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); screenIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); return screenIntent; }
同时清单文件也要设置一些必要的属性:
<activity android:name=".LockScreenActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:excludeFromRecents="true" android:exported="true" android:hardwareAccelerated="true" android:launchMode="singleInstance" android:taskAffinity="com.lock.LockScreenActivity" android:theme="@style/LockScreenStyle" android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
最重要的还是权限:有些10.0手机需要赋予在应用上层显示的权限,有些10.0则不需要,参考喜马拉雅App和酷狗都是需要的
<!--10.0专属,在其他应用上层展示--> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
附上demo地址: