Android设备管理(锁屏、恢复出厂设置、设置密码、设置屏幕灯光等操作)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ly0904010214/article/details/24286563

 Android 2.2 SDK提供了一个可管理和操作设备的API叫DevicePolicyManager,使用这个API你可以接管手机的应用权限,对手机做出很多大胆的操作,比如锁屏,恢复出厂设置,还有设置密码、强制清除密码,修改密码、设置屏幕灯光渐暗时间间隔等操作。

 

具体步骤如下:

1、首先需要自定义一个 DeviceAdminReceiver 类,用以监听权限的变化。

在AndroidManifest.xml中注册广播类

 

<receiver android:name=".deviceAdminReceiver" android:label="@string/app_name"
            android:description="@string/description" 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>


android:permission ="android.app.action.DEVICE_ADMIN_ENABLED"

表示此功能需要的权限

<meta-data android:name="android.app.device_admin"
android:resource
="@xml/device_admin"/>

表示此动作的跳转界面

定义广播类的java代码

 

public class deviceAdminReceiver extends DeviceAdminReceiver {

    /**
     * 获取设备存储的数值
     * 
     * @param context
     * @return
     */
    public static SharedPreferences getDevicePreference(Context context) {
        return context.getSharedPreferences(
                DeviceAdminReceiver.class.getName(), 0);
    }

    // 密码的特点
    public static String PREF_PASSWORD_QUALITY = "password_quality";
    // 密码的长度
    public static String PREF_PASSWORD_LENGTH = "password_length";

    public static String PREF_MAX_FAILED_PW = "max_failed_pw";

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

    @Override
    public void onEnabled(Context context, Intent intent) {
        // TODO Auto-generated method stub
        showToast(context, "设备管理:可用");
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        // TODO Auto-generated method stub
        showToast(context, "设备管理:不可用");
    }
}

 

2、在layout中定义界面上几个简单的组件

 

<Button
	    android:id="@+id/enable_admin"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="启用管理"
	    />
	<Button
	    android:id="@+id/disable_admin"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="停用管理"
	    />
    <Button
	    android:id="@+id/force_lock"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="锁屏"
	    />
    <Button
	    android:id="@+id/time_out"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="设置屏幕光亮间隔"
	    />
    <EditText
	    android:id="@+id/et_time_out"
	    android:layout_width="100dip"
	    android:layout_height="50dip"
	    />
    <Button
        android:id="@+id/reset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="恢复出厂设置"
        />


3、在activity中定义组件的事件处理程序

 

public class MainActivity extends Activity
{

    static final int RESULT_ENABLE = 1;
    DevicePolicyManager mDPM;
    ActivityManager mAM;
    ComponentName mDeviceComponentName;
    Button enableAdmin, disableAdmin, force_lock, btn_time_out, reset;
    EditText et;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        mAM = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        mDeviceComponentName = new ComponentName(MainActivity.this,
                deviceAdminReceiver.class);
        setContentView(R.layout.activity_main);

        findView();

        init();

    }

    void findView() {
        enableAdmin = (Button) findViewById(R.id.enable_admin);
        disableAdmin = (Button) findViewById(R.id.disable_admin);
        force_lock = (Button) findViewById(R.id.force_lock);
        btn_time_out = (Button) findViewById(R.id.time_out);
        et = (EditText) findViewById(R.id.et_time_out);
        reset = (Button) findViewById(R.id.reset);
    }

    void init() {
        enableAdmin.setOnClickListener(new enableAdminClickEvent());
        disableAdmin.setOnClickListener(new disableAdminClickEvent());
        force_lock.setOnClickListener(new force_lock());
        btn_time_out.setOnClickListener(new timeoutClickEvent());
        reset.setOnClickListener(new resetClickEvent());
    }

    void updateButtonState() {
        boolean active = mDPM.isAdminActive(mDeviceComponentName);
        if (active) {
            enableAdmin.setEnabled(false);
            disableAdmin.setEnabled(true);
            force_lock.setEnabled(true);
            btn_time_out.setEnabled(true);
            reset.setEnabled(true);
        } else {
            enableAdmin.setEnabled(true);
            disableAdmin.setEnabled(false);
            force_lock.setEnabled(false);
            btn_time_out.setEnabled(false);
            reset.setEnabled(false);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        updateButtonState();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        switch (requestCode) {
        case RESULT_ENABLE:
            if (resultCode == Activity.RESULT_OK) {
                Log.v("DeviceEnable", "deviceAdmin:enable");
            } else {
                Log.v("DeviceEnable", "deviceAdmin:disable");
            }
            break;

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 设备管理可用的点击事件
     * 
     * @author terry
     * 
     */
    class enableAdminClickEvent implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(
                    DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                    mDeviceComponentName);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                    "这里可以输入一些额外的说明,比如提示用户什么的");
            startActivityForResult(intent, RESULT_ENABLE);
        }

    }

    /**
     * 设备管理不可用的点击事件
     * 
     * @author terry
     * 
     */
    class disableAdminClickEvent implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mDPM.removeActiveAdmin(mDeviceComponentName);
            updateButtonState();
        }

    }

    /**
     * 锁屏
     * 
     * @author terry
     * 
     */
    class force_lock implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mAM.isUserAMonkey()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
                builder.setMessage("你不能对此屏幕进行操作,因为你不是管理员");
                builder.setPositiveButton("I admit defeat", null);
                builder.show();
                return;
            }
            boolean active = mDPM.isAdminActive(mDeviceComponentName);
            if (active) {
                mDPM.lockNow();
            }
        }
    }

    /**
     * 屏幕自动变暗
     * 
     * @author terry
     * 
     */
    class timeoutClickEvent implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mAM.isUserAMonkey()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
                builder.setMessage("你不能对我的屏幕进行操作,因为你不是管理员");
                builder.setPositiveButton("I admit defeat", null);
                builder.show();
                return;
            }
            boolean active = mDPM.isAdminActive(mDeviceComponentName);
            if (active) {
                long timeout = 1000L * Long.parseLong(et.getText().toString());
                mDPM.setMaximumTimeToLock(mDeviceComponentName, timeout);
            }
        }
    }

    /**
     * 恢复出厂设置
     * 
     * @author terry
     * 
     */
    class resetClickEvent implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mAM.isUserAMonkey()) {
                // Don't trust monkeys to do the right thing!
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
                builder
                        .setMessage("You can't wipe my data because you are a monkey!");
                builder.setPositiveButton("I admit defeat", null);
                builder.show();
                return;
            }

            AlertDialog.Builder builder = new Builder(MainActivity.this);
            builder.setMessage("将重置数据,你确定此操作吗?");
            builder.setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            AlertDialog.Builder aler = new AlertDialog.Builder(
                                    MainActivity.this);
                            aler.setMessage("删除数据后,系统将会重新启动.确定吗?");
                            aler.setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method stub
                                            boolean active = mDPM
                                                    .isAdminActive(mDeviceComponentName);
                                            if (active) {
                                                mDPM.wipeData(0);
                                            }
                                        }
                                    });
                            aler
                                    .setNeutralButton(android.R.string.cancel,
                                            null);
                            aler.show();
                        }
                    });
            builder.setNeutralButton(android.R.string.cancel, null);
            builder.show();
        }
    }


}


 

注:

1、getSystemService是Android很重要的一个API,它是Activity的一个方法,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。

 

传入的Name | 返回的对象 | 说明

  • WINDOW_SERVICE WindowManager 管理打开的窗口程序
  • LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定义的view
  • ACTIVITY_SERVICE ActivityManager 管理应用程序的系统状态
  • POWER_SERVICE PowerManger 电源的服务
  • ALARM_SERVICE AlarmManager 闹钟的服务
  • NOTIFICATION_SERVICE NotificationManager 状态栏的服务
  • KEYGUARD_SERVICE KeyguardManager 键盘锁的服务
  • LOCATION_SERVICE LocationManager 位置的服务,如GPS
  • SEARCH_SERVICE SearchManager 搜索的服务
  • VEBRATOR_SERVICE Vebrator 手机震动的服务
  • CONNECTIVITY_SERVICE Connectivity 网络连接的服务
  • WIFI_SERVICE WifiManager Wi-Fi服务
  • TELEPHONY_SERVICE TeleponyManager 电话服务

 

 

Currently available names are:

  • WINDOW_SERVICE ("window")
    The top-level window manager in which you can place custom windows. The returned object is a WindowManager.
  • LAYOUT_INFLATER_SERVICE ("layout_inflater")
    A LayoutInflater for inflating layout resources in this context.
  • ACTIVITY_SERVICE ("activity")
    A ActivityManager for interacting with the global activity state of the system.
  • POWER_SERVICE ("power")
    A PowerManager for controlling power management.
  • ALARM_SERVICE ("alarm")
    A AlarmManager for receiving intents at the time of your choosing.
  • NOTIFICATION_SERVICE ("notification")
    A NotificationManager for informing the user of background events.
  • KEYGUARD_SERVICE ("keyguard")
    A KeyguardManager for controlling keyguard.
  • LOCATION_SERVICE ("location")
    A LocationManager for controlling location (e.g., GPS) updates.
  • SEARCH_SERVICE ("search")
    A SearchManager for handling search.
  • VIBRATOR_SERVICE ("vibrator")
    A Vibrator for interacting with the vibrator hardware.
  • CONNECTIVITY_SERVICE ("connection")
    A ConnectivityManager for handling management of network connections.
  • WIFI_SERVICE ("wifi")
    A WifiManager for management of Wi-Fi connectivity.
  • INPUT_METHOD_SERVICE ("input_method")
    An InputMethodManager for management of input methods.
  • UI_MODE_SERVICE ("uimode")
    An UiModeManager for controlling UI modes.
  • DOWNLOAD_SERVICE ("download")
    A DownloadManager for requesting HTTP downloads

 

Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)

2、

ComponentName是用来打开其他应用程序中的Activity或服务的。

用法:

Intent i=new Intent();
i.setComponent(new ComponentName(String packageName,String activityName ));
startActivity(i);

3

isUserAMonkey()

Returns "true" if the user interface is currently being messed with by a monkey.

 

 

 

 

 

 

 

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页