不想看文檔能夠直接拉到後面,代碼將在後面貼出html
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.java
系統管理員可使用設備管理API去編寫一個能夠執行遠程或者本地設備安全策略實施的應用程序,本章節總結了建立一個設備管理應用所涉及的步驟 android
建立manifest文件express
To use the Device Administration API, the application's manifest must include the following:api
使用設備管理API的應用程序的manifest文件必須包含如下內容: 安全
一個繼承了DeviceAdminReceive的子類需包含如下內容 app
A subclass of DeviceAdminReceiver
that includes the following:ide
The BIND_DEVICE_ADMIN
permission.須要BIND_DEVICE_ADMIN權限
函數
The ability to respond to the ACTION_DEVICE_ADMIN_ENABLED
intent, expressed in the manifest as an intent filter.ui
需在manifest文件中聲明 intent filter 使其可以對ACTION_DEVICE_ADMIN_ENABLED的意圖作出迴應
A declaration of security policies used in metadata.
在聲明中包含安全策略的元數據
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
如下屬性可參考例子程序中的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.
實現代碼部分
The Device Administration API includes the following classes:
設備管理API包含如下類
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的子類
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
在設備上管理策略實施的一個類,正在使用該類的大多數類必須有一個公開的DeviceAdminReceiver。
DevicePolicyManager管理一個或者多個的
DeviceAdminReceiver的策略
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.
這些類爲設備管理程序提供了功能齊全的功能函數。後面的部分藐視瞭如何使用DeviceAdminReceiver和
DevicePolicyManager API去寫一個設備管理程序
To create a device admin application, you must subclass DeviceAdminReceiver
. The DeviceAdminReceiver
class 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)); } ... }
受權程序
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) { /*一、先清除管理員權限*/ ComponentName mDeviceAdminSample = new ComponentName(this, MyAdmin.class); dpm.removeActiveAdmin(mDeviceAdminSample); /*二、普通應用卸載*/ 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); } }