问题
I want to display one Activity Android, also when I lock my device. Every Time, if I lock my tablet (for example), I should to see one Activity.
So, I have built this in AndroidManifest.xml:
<activity
android:name=".activity.SetupInfoEmergencyActivity"
android:label="@string/app_name"
android:showOnLockScreen="true"
android:screenOrientation="sensorPortrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This is the code of activity
public class SetupInfoEmergencyActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
}
}
Now, if I try to run debug, I can see this activity, but if I un-lock my device, and I lock the device I can't see the activity.
回答1:
use this code in last of method onCreate
//show if unlock
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
回答2:
Don't use an activity. Android will not show the lock screen behind your activity for security reason, so use service instead of Activity.
Below is my code in onStartCommand of my service.
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
View mView = mInflater.inflate(R.layout.score, 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
/* | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON */,
PixelFormat.RGBA_8888);
mWindowManager.addView(mView, mLayoutParams);
And add uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" to manifest
This is copy from another similar post. I tried it real quick with a custom view and it worked well enough. Don't know what your intentions are for it though.
来源:https://stackoverflow.com/questions/37325587/how-can-i-display-the-activity-when-device-is-locked