只需点击应用图标即可锁定Android屏幕

时间:2014-09-30 05:39:27

标签: android screen-lock

我想创建应用程序,当我点击我的应用程序图标,屏幕自动锁定时,请任何人帮我如何做到这一点?

我在谷歌搜索但没有找到这样的,所以请帮我做。

在此我单击app_launcher图标并直接锁定移动屏幕。

2 个答案:

答案 0 :(得分:1)

尝试此代码(锁定屏幕和屏幕关闭):

public DevicePolicyManager deviceAdminPolicyManager = (DevicePolicyManager)getSystemService( Context.DEVICE_POLICY_SERVICE);
public ComponentName deviceAdminComponentName = new ComponentName( this, DeviceAdmin.class);

deviceAdminPolicyManager.lockNow();
PowerManager powerManager = (PowerManager) getSystemService( Context.POWER_SERVICE);
if( powerManager.isScreenOn()) powerManager.goToSleep( System.currentTimeMillis() + 1000L);

您的应用必须由设置 - 安全 - 设备管理员添加为设备管理员。

还添加Manifest:

<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.DEVICE_POWER"/> <!-- for screen off and on -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>

 <receiver android:label="@string/label" android:name="com.package$DeviceAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
  <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin" />
  <intent-filter>
   <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
  </intent-filter>
 </receiver>

public  static class DeviceAdmin extends DeviceAdminReceiver
 {
   public CharSequence onDisableRequested( Context paramContext, Intent paramIntent) { return ""; }
   public void onDisabled( Context paramContext, Intent paramIntent) {}
   public void onEnabled( Context paramContext, Intent paramIntent) {}
   public void onPasswordChanged( Context paramContext, Intent paramIntent) {}
 }

DeviceAdmin.xml

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

答案 1 :(得分:0)

//For Unlock  

WindowManager winManager = Context.getSystemService(Context.WINDOW_SERVICE);    
Window window = getWindow();      
window.addFlags(winManager.LayoutParams.FLAG_DISMISS_KEYGUARD); 

OR

    KeyguardManager km = (KeyguardManager) context
     .getSystemService(Context.KEYGUARD_SERVICE);
   final KeyguardManager.KeyguardLock kl = km
     .newKeyguardLock("MyKeyguardLock");
   kl.disableKeyguard();

   PowerManager pm = (PowerManager) context
     .getSystemService(Context.POWER_SERVICE);
   WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
     | PowerManager.ACQUIRE_CAUSES_WAKEUP
     | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
   wakeLock.acquire(); 


//Lock device

DevicePolicyManager myDPM;    
myDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);