我想创建一个应用程序,其中一些信息对用户可见 在锁定屏幕上。我在互联网上搜索过。我发现,出于安全原因,android不允许锁定屏幕顶部的活动布局。 正如有人建议我尝试使用服务和WindowManger。 以下是我上网的代码。
public class MyService extends Service {
WindowManager mWindowManager;
View mView;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerOverlayReceiver();
return super.onStartCommand(intent, flags, startId);
}
private void showDialog(){
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
View mView = View.inflate(getApplicationContext(),R.layout.activity_main, null);
WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
PixelFormat.RGBA_8888);
mView.setVisibility(View.VISIBLE);
mWindowManager.addView(mView, mLayoutParams);
}
private void hideDialog(){
if(mView != null && mWindowManager != null){
mWindowManager.removeView(mView);
mView = null;
}
}
@Override
public void onDestroy() {
unregisterOverlayReceiver();
super.onDestroy();
}
private void registerOverlayReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(overlayReceiver, filter);
}
private void unregisterOverlayReceiver() {
hideDialog();
unregisterReceiver(overlayReceiver);
}
private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_ON)) {
showDialog();
}
else if (action.equals(Intent.ACTION_USER_PRESENT)) {
hideDialog();
}
else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
hideDialog();
}
}
};
}
我理解这段代码。但是当我尝试这段代码时。这不起作用。 我许可了
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"></uses-permission>
任何人都可以帮我解决这个问题吗?