简单几步实现Android 一键锁屏,一键卸载程序,一键激活设备管理权限

以下为官方的文档(本人能力有限,尝试着翻译下,有错请指出)

不想看文档可以直接拉到后面,代码将在后面贴出

Developing a Device Administration Application

System administrators can use the Device Administration API to write an application that enforces(实施v) remote/local device security policy enforcement(实施n). This section(章节) summarizes(总结) the steps involved in creating a device administration application.

系统管理员可以使用设备管理API去编写一个可以执行远程或者本地设备安全策略实施的应用程序,本章节总结了创建一个设备管理应用所涉及的步骤

Creating the manifest

创建manifest文件

To use the Device Administration API, the application's manifest must include the following:

使用设备管理API的应用程序的manifest文件必须包含以下内容:

一个继承了DeviceAdminReceive的子类需包含以下内容

Here is an excerpt from the Device Administration sample manifest:

这是来自设备管理例子的manifest文件,可作为参考

<activity android:name=".app.DeviceAdminSample"
            android:label="@string/activity_sample_device_admin">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.SAMPLE_CODE" />
    </intent-filter>
</activity>
<receiver android:name=".app.DeviceAdminSample$DeviceAdminSampleReceiver"
        android:label="@string/sample_device_admin"
        android:description="@string/sample_device_admin_description"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
    <meta-data android:name="android.app.device_admin"
            android:resource="@xml/device_admin_sample" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>
</receiver>

Note that:

  • The following attributes refer to string resources that for the sample application reside inApiDemos/res/values/strings.xml. For more information about resources, see

  • Application Resources.

  • 以下属性可参考例子程序中的ApiDemos/res/values/strings.xml. 字符资源文件,更多详细信息请查看Application Resources.


    • android:label="@string/activity_sample_device_admin" refers to the user-readable label for the activity.

    • android:label="@string/sample_device_admin" refers to the user-readable label for the permission.

    • android:description="@string/sample_device_admin_description" refers to the user-readable description of the permission. A descripton is typically longer and more informative than a label.

  • android:permission="android.permission.BIND_DEVICE_ADMIN" is a permission that aDeviceAdminReceiver subclass must have, to ensure that only the system can interact with the receiver (no application can be granted this permission ). This prevents other applications from abusing your device admin app.

  • 必须有一个receiver类型的子类,只有其能够与系统交互(没有应用可以被授予该权限)这样阻止了其他程序滥用你的设备管理app

  • android.app.action.DEVICE_ADMIN_ENABLED is the primary action that a DeviceAdminReceiver subclass must handle to be allowed to manage a device. This is set to the receiver when the user enables the device admin app. Your code typically handles this in onEnabled(). To be supported, the receiver must also require the BIND_DEVICE_ADMIN permission so that other applications cannot abuse it.

  •  继承DeviceAdminReceiver的子类DeviceAdminReceiver是一个主要的action,该子类必须被允许去操作设置管理程序。设置一个receiver去接受在用户操作设备管理程序时返回的数据。你的代码通常在onEnabled()内进行操作,receiver避居具备BIND_DEVICE_ADMIN权限的支持,增加权限的目的是以便其他程序不能滥用它

  • When a user enables the device admin application, that gives the receiver permission to perform actions in response to the broadcast of particular system events. When suitable event arises, the application can impose a policy. For example, if the user attempts to set a new password that doesn't meet the policy requirements, the application can prompt the user to pick a different password that does meet the requirements.

  • 当一个用户使用设备管理程序的同时也就给予了receiver一定的权限去执行操作来响应特定的系统时间的广播,在适当的事件发生时,该程序可以执行一个策略,例如:如果用户尝试去设置一个新的不符合策略要求的密码,该程序可以提示用户去选择一个满足要求的密码

  • android:resource="@xml/device_admin_sample" declares the security policies used in metadata. The metadata provides additional information specific to the device administrator, as parsed by theDeviceAdminInfo class. Here are the contents of device_admin_sample.xml:

  • 声明中使用的安全策略的元数据提供了特定于设备管理员的附加信息,可通过DeviceAdminInfo类进行解析查看,以下为device_admin_sample.xml:的内容

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
  <uses-policies>
    <limit-password />
    <watch-login />
    <reset-password />
    <force-lock />
    <wipe-data />
    <expire-password />
    <encrypted-storage />
    <disable-camera />
  </uses-policies>
</device-admin>

In designing your device administration application, you don't need to include all of the policies, just the ones that are relevant for your app.

在设计你的设备管理程序时,你不需要加入所有的策略,只需要加入与你的程序有关的即可。

For more discussion of the manifest file, see the Android Developers Guide.

对于manifest文件更多的讨论可以查看Android Developers Guide.

Implementing the code

实现代码部分

The Device Administration API includes the following classes:

设备管理API包含以下类

  • DeviceAdminReceiver

  • Base class for implementing a device administration component. This class provides a convenience for interpreting the raw intent actions that are sent by the system. Your Device Administration application must include a DeviceAdminReceiver subclass.

  • 该类为实现一个设备管理组件的基本类,这个类提供了一个方便去解析系统发送的原始意图的行为,你的设备管理程序必须包含一个DeviceAdminReceiver的子类

  • DevicePolicyManager

  • A class for managing policies enforced on a device. Most clients of this class must have published aDeviceAdminReceiver that the user has currently enabled. The DevicePolicyManager manages policies for one or more DeviceAdminReceiver instances

  • 在设备上管理策略实施的一个类,正在使用该类的大多数类必须有一个公开的DeviceAdminReceiverDevicePolicyManager管理一个或者多个的DeviceAdminReceiver的策略

  •  

  • DeviceAdminInfo

  • This class is used to specify metadata for a device administrator component.

  • 这个类通常是为设备管理员组件制定元数据

These classes provide the foundation for a fully functional device administration application. The rest of this section describes how you use the DeviceAdminReceiver and DevicePolicyManager APIs to write a device admin application.

这些类为设备管理程序提供了功能齐全的功能函数。后面的部分藐视了如何使用DeviceAdminReceiverDevicePolicyManager API去写一个设备管理程序

Subclassing DeviceAdminReceiver

To create a device admin application, you must subclass DeviceAdminReceiver. The DeviceAdminReceiverclass consists of a series of callbacks that are triggered when particular events occur.

创建一个设备管理程序,你必须有一个DeviceAdminReceiver的子类,DeviceAdminReceiver包含了一系列的回调函数在特别的事件发生时触发

In its DeviceAdminReceiver subclass, the sample application simply displays a Toast notification in response to particular events. For example:

DeviceAdminReceiver子类中,这示例程序简单的展示了一个响应特定事件的Toast 通知

public class DeviceAdminSample extends DeviceAdminReceiver {

    void showToast(Context context, String msg) {
        String status = context.getString(R.string.admin_receiver_status, msg);
        Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onEnabled(Context context, Intent intent) {
        showToast(context, context.getString(R.string.admin_receiver_status_enabled));
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return context.getString(R.string.admin_receiver_status_disable_warning);
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        showToast(context, context.getString(R.string.admin_receiver_status_disabled));
    }

    @Override
    public void onPasswordChanged(Context context, Intent intent) {
        showToast(context, context.getString(R.string.admin_receiver_status_pw_changed));
    }
...
}
Enabling the application

授权程序

One of the major events a device admin application has to handle is the user enabling the application. The user must explicitly enable the application for the policies to be enforced. If the user chooses not to enable the application it will still be present on the device, but its policies will not be enforced, and the user will not get any of the application's benefits.

一个设备管理程序的主要事件是必须处理用户的授权程序,用户必须显示地操作授予权限的程序,

如果用户选择不授予该权限,该程序仍然能够继续在设备上执行,但是该需要权限的部分将不被执行。

The process of enabling the application begins when the user performs an action that triggers theACTION_ADD_DEVICE_ADMIN intent. In the sample application, this happens when the user clicks the Enable Admin checkbox.

在用户执行该程序时,授权程序将被执行,此时将触发ACTION_ADD_DEVICE_ADMIN意图,在该示例程序中当用户点击EnableAdmin 选择框时将被执行

When the user clicks the Enable Admin checkbox, the display changes to prompt the user to activate the device admin application, as shown in figure 2.

Figure 2. Sample Application: Activating the Application

Below is the code that gets executed when the user clicks the Enable Admin checkbox. This has the effect of triggering the onPreferenceChange() callback. This callback is invoked when the value of this Preference has been changed by the user and is about to be set and/or persisted. If the user is enabling the application, the display changes to prompt the user to activate the device admin application, as shown in figure 2. Otherwise, the device admin application is disabled.

@Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (super.onPreferenceChange(preference, newValue)) {
                return true;
            }
            boolean value = (Boolean) newValue;
            if (preference == mEnableCheckbox) {
                if (value != mAdminActive) {
                    if (value) {
                        // Launch the activity to have the user enable our admin.
                        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);
                        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                                mActivity.getString(R.string.add_admin_extra_app_text));
                        startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
                        // return false - don't update checkbox until we're really active
                        return false;
                    } else {
                        mDPM.removeActiveAdmin(mDeviceAdminSample);
                        enableDeviceCapabilitiesArea(false);
                        mAdminActive = false;
                    }
                }
            } else if (preference == mDisableCameraCheckbox) {
                mDPM.setCameraDisabled(mDeviceAdminSample, value);
                ...
            }
            return true;
        }

The line intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample) states thatmDeviceAdminSample (which is a DeviceAdminReceiver component) is the target policy. This line invokes the user interface shown in figure 2, which guides users through adding the device administrator to the system (or allows them to reject it).

When the application needs to perform an operation that is contingent on the device admin application being enabled, it confirms that the application is active. To do this it uses the DevicePolicyManager methodisAdminActive(). Notice that the DevicePolicyManager method isAdminActive() takes aDeviceAdminReceiver component as its argument:

DevicePolicyManager mDPM;
...
private boolean isActiveAdmin() {
    return mDPM.isAdminActive(mDeviceAdminSample);
}
 
好了,直接贴代码:
第一步:根据文档
创建子类
package com.zaizai.locksreen;

import android.app.admin.DeviceAdminReceiver;

/**
 * Created by zaizai on 2015/11/3.
 */
public class MyAdmin extends DeviceAdminReceiver {
}

在manifest文件中声明

<receiver android:name=".MyAdmin">
    android:label="@string/用户管理员"
    android:description="@string/用户管理员描述信息"
    android:permission="android.permission.BIND_DEVICE_ADMIN">
    <meta-data android:name="android.app.device_admin"
        android:resource="@xml/device_admin_sample" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>

</receiver>
在activity文件中使用
package com.zaizai.locksreen;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    /**
     * 设备策略服务
     */
    private DevicePolicyManager dpm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);


    }

    public void lockScreen(View view) {
        ComponentName cn = new ComponentName(this, MyAdmin.class);
        if(dpm.isAdminActive(cn)){
            //设备管理员的api
            dpm.resetPassword("", 0);
            dpm.lockNow();
//       dpm.wipeData(0);
//       dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//删除sdcard数据
        }else{
//       openAdmin(null);
            Toast.makeText(this, "请先激活管理员",Toast.LENGTH_LONG).show();
        }

        /*设置屏幕密码*/
        //dpm.resetPassword("123",0);
        /*清楚数据*/
        //dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
        /*恢复出厂设置*/
        //dpm.wipeData(0);
    }

    /**
     * 用代码开启管理员权限
     *
     * @param view
     */

    public void openAdmin(View view) {
        /*创建添加设备管理员的意图*/
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        /*设置需要激活的组件*/
        ComponentName mDeviceAdminSample = new ComponentName(this, MyAdmin.class);

        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);
        /*给用户提示。给出开启的理由*/
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                "开启即可实现一键锁屏");
        startActivity(intent);

    }

    /**
     * 卸载当前软件
     *
     * @param view
     */
    public void uninstall(View view) {
        /*1、先清除管理员权限*/
        ComponentName mDeviceAdminSample = new ComponentName(this, MyAdmin.class);
        dpm.removeActiveAdmin(mDeviceAdminSample);
        /*2、普通应用卸载*/
        Intent intent = new Intent();
        intent.setAction("android.intent.action.UNINSTALL_PACKAGE");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

转载于:https://my.oschina.net/zaizaiangels/blog/525410

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值