如何从应用程序启动默认的Android锁定屏幕,而不是按两次电源按钮?

时间:2014-08-11 05:07:26

标签: android android-intent android-activity sleep lockscreen

是否存在与锁定屏幕关联的意图,以便我可以从我的应用程序启动锁定屏幕?或从应用程序启动锁定屏幕的任何其他方式?我尝试使用goToSleep和wakeUp方法(http://developer.android.com/reference/android/os/PowerManager.html)这样,我可以强制锁定屏幕。但该应用程序没有DEVICE_POWER(http://developer.android.com/reference/android/Manifest.permission.html#DEVICE_POWER)的权限。有什么建议吗?

1 个答案:

答案 0 :(得分:-1)

1)在onCreate中添加此意图以提供Device_Admin权限

Intent intent = new Intent(DevicePolicyManager  
                    .ACTION_ADD_DEVICE_ADMIN);  
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,  
                    compName);  
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  
                    "");  
            startActivityForResult(intent, RESULT_ENABLE);  

2)在清单中添加接收器类:

 <receiver
                android:name="com.example.AdminReceiver"
                android:permission="android.permission.BIND_DEVICE_ADMIN" >
                <meta-data
                    android:name="android.app.device_admin"
                    android:resource="@layout/policies" >
                    <intent-filter>
                        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" >
                        </action>
                    </intent-filter>
                </meta-data>
            </receiver>

3)添加扩展DeviceAdminReceiver的Receiver类

    public class AdminReceiver extends DeviceAdminReceiver{  


        static SharedPreferences getSamplePreferences(Context context) {  
            return context.getSharedPreferences(  
              DeviceAdminReceiver.class.getName(), 0);  
        }  
 }

4)在布局文件夹中添加XML文件(policies.xml)

<!-- ?xml version="1.0" encoding="utf-8"? -->
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >

    <uses-policies>
        <limit-password>
            <watch-login>
                <reset-password>
                    <force-lock>
                        <wipe-data>
                        </wipe-data>
                    </force-lock>
                </reset-password>
            </watch-login>
        </limit-password>
    </uses-policies>

</device-admin>