繁体   English   中英

如何以编程方式锁定/解锁屏幕?

[英]How to Lock/Unlock screen programmatically?

我正在做一个在抖动时锁定屏幕的应用程序。 现在它正在锁定,如果屏幕关闭,它就会从那里转到广播接收器,它进入必须打开屏幕的服务。

下面是广播接收器:

  public class ScreenReceiver extends BroadcastReceiver {   
    public static boolean wasScreenOn = true;
    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("Entered Broadcaste Reciever");

        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // DO WHATEVER YOU NEED TO DO HERE
             System.out.println("SCREEN_OFF"+wasScreenOn);
            wasScreenOn = false;

            Intent i = new Intent(context, UpdateService.class);
            i.putExtra("screen_state", wasScreenOn);
            context.startService(i);

            System.out.println("jrkejhr keh");
        }
        else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // AND DO WHATEVER YOU NEED TO DO HERE
            wasScreenOn = true;
            System.out.println("SCREEN_ON"+wasScreenOn);
        }
    }

它进入我写回家的意图行动的服务是......

  ShakeListener mShaker;
    int amountOfTime = 0;
    Context context1;   
    @Override   
         public void onCreate() {

            super.onCreate();

            // REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
            System.out.println("Enterd Service");
            final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

            mShaker = new ShakeListener(this);
            mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
              public void onShake() {
                vibe.vibrate(100);
                Intent goHome = new Intent();
                goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                goHome.setAction("android.intent.action.MAIN");
                goHome.addCategory("android.intent.category.HOME");
                startActivity(goHome);                      
               }
            });
         }
       @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
     }

它正在进入服务。 但是主屏幕没有显示。 当服务被调用时,屏幕被锁定。

编辑:

由于有些人需要在以编程方式锁定后解锁设备方面的帮助,我通过了以编程方式锁定/解锁Android屏幕后的帖子,请查看,可能对您有所帮助。

原答案是:

您需要获得管理员权限才能锁定手机屏幕

请查看下面的简单教程以实现这一目标

以编程方式锁定手机屏幕

这里也是代码示例..

锁屏活动.java

public class LockScreenActivity extends Activity implements OnClickListener {  
 private Button lock;  
 private Button disable;  
 private Button enable;  
 static final int RESULT_ENABLE = 1;  

     DevicePolicyManager deviceManger;  
     ActivityManager activityManager;  
     ComponentName compName;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        deviceManger = (DevicePolicyManager)getSystemService(  
          Context.DEVICE_POLICY_SERVICE);  
        activityManager = (ActivityManager)getSystemService(  
          Context.ACTIVITY_SERVICE);  
        compName = new ComponentName(this, MyAdmin.class);  

        setContentView(R.layout.main);  

        lock =(Button)findViewById(R.id.lock);  
        lock.setOnClickListener(this);  

        disable = (Button)findViewById(R.id.btnDisable);  
        enable =(Button)findViewById(R.id.btnEnable);  
        disable.setOnClickListener(this);  
        enable.setOnClickListener(this);  
    }  

 @Override  
 public void onClick(View v) {  

  if(v == lock){  
    boolean active = deviceManger.isAdminActive(compName);  
             if (active) {  
                 deviceManger.lockNow();  
             }  
  }  

  if(v == enable){  
   Intent intent = new Intent(DevicePolicyManager  
     .ACTION_ADD_DEVICE_ADMIN);  
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,  
                    compName);  
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  
                    "Additional text explaining why this needs to be added.");  
            startActivityForResult(intent, RESULT_ENABLE);  
  }  

  if(v == disable){  
     deviceManger.removeActiveAdmin(compName);  
              updateButtonStates();  
  }    
 }  

 private void updateButtonStates() {  

        boolean active = deviceManger.isAdminActive(compName);  
        if (active) {  
            enable.setEnabled(false);  
            disable.setEnabled(true);  

        } else {  
            enable.setEnabled(true);  
            disable.setEnabled(false);  
        }      
 }  

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
         switch (requestCode) {  
             case RESULT_ENABLE:  
                 if (resultCode == Activity.RESULT_OK) {  
                     Log.i("DeviceAdminSample", "Admin enabled!");  
                 } else {  
                     Log.i("DeviceAdminSample", "Admin enable FAILED!");  
                 }  
                 return;  
         }  
         super.onActivityResult(requestCode, resultCode, data);  
     }  
}

我的管理程序

public class MyAdmin extends DeviceAdminReceiver{  


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

    static String PREF_PASSWORD_QUALITY = "password_quality";  
    static String PREF_PASSWORD_LENGTH = "password_length";  
    static String PREF_MAX_FAILED_PW = "max_failed_pw";  

    void showToast(Context context, CharSequence msg) {  
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
    }  

    @Override  
    public void onEnabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: enabled");  
    }  

    @Override  
    public CharSequence onDisableRequested(Context context, Intent intent) {  
        return "This is an optional message to warn the user about disabling.";  
    }  

    @Override  
    public void onDisabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: disabled");  
    }  

    @Override  
    public void onPasswordChanged(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw changed");  
    }  

    @Override  
    public void onPasswordFailed(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw failed");  
    }  

    @Override  
    public void onPasswordSucceeded(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw succeeded");  
    }  

}

使用Activity.getWindow()获取您的活动窗口; 使用Window.addFlags()WindowManager.LayoutParams中添加您想要的以下任一标志:

示例页面上的 androidmanifest.xml 和 policies.xml 文件在我的浏览器中不可见,因为它试图将 XML 文件格式化为 HTML。 我只是为了方便他人而发布此内容以供参考,此内容来自示例页面。

感谢大家提出这个有用的问题!

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kns"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LockScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

    </application>
</manifest>

政策文件

<?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 />
    </uses-policies>
</device-admin>

访问 android 开发者链接并从示例应用程序中读取锁定

https://developer.android.com/guide/topics/admin/device-admin

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM