1.节约电量方式&关闭系统动画
2.sim卡的绑定
(1)每张卡有唯一的序列号 (2)为什么不绑定手机号码呢?
因为有些SIM卡里没有写入手机号码,比如移动的卡和联通的卡等等 (3)获取sim卡的序列号
<span style="font-size:14px;">/**
* 读取手机sim的信息,系统服务
*/
private TelephonyManager tm;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);//实例化
//获取sim卡的序列号
String sim = tm.getSimSerialNumber();
// getLine1Number() 获取SIM卡绑定的号码</span>
(4)加权限 android:name="android.permission.READ_PHONE_STATE"
3.检查手机是否变更SIM卡
(1)广播接收者监听手机开机( public class BootCompleteReceiver extends BroadcastReceiver ) a. 广播接收者需要在清单文件中配置
<receiver android:name="com.itheima.mobilesafe.receiver.BootCompleteReceiver" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
b.监听手机开机需要权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
c. 广播接收者代码
public class BootCompleteReceiver extends BroadcastReceiver {
private SharedPreferences sp;
private TelephonyManager tm;
@Override
public void onReceive(Context context, Intent intent) {
sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
boolean protecting = sp.getBoolean("protecting", false);
if(protecting){
//开启防盗保护才执行这个地方
tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// 读取之前保存的SiM信息;
String saveSim = sp.getString("sim", "")+"afu";
//读取当前的sim卡信息
String realSim = tm.getSimSerialNumber();
//比较是否一样
if(saveSim.equals(realSim)){
//sim没有变更,还是同一个哥们
}else{
// sim 已经变更 发一个短信给安全号码
System.out.println("sim 已经变更");
Toast.makeText(context, "sim 已经变更", 1).show();
SmsManager.getDefault().sendTextMessage(sp.getString("safenumber", ""), null, "sim changing....", null, null);
}
}
}
}
4.读取联系人的结构
(1)新建一个Activity(带Listview)
5.读取联系人
(1)读取联系人权限 READ_CONTACTS (2)总布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:background="#8866ff00"
android:gravity="center"
android:text="选择联系人"
android:textColor="#000000"
android:textSize="22sp" />
<ListView
android:id="@+id/list_select_contact"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dip"
android:verticalSpacing="10dip" />
</LinearLayout>
(3)item布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名"
android:textColor="#ff0000"
android:textSize="22sp" />
<TextView
android:id="@+id/tv_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@android:drawable/ic_menu_call"
android:text="5558"
android:textColor="#000000"
android:textSize="22sp" />
</LinearLayout>
(4)代码
public class SelectContactActivity extends Activity {
private ListView list_select_contact;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_contact);
list_select_contact = (ListView) findViewById(R.id.list_select_contact);
final List<Map<String, String>> data = getContactInfo();
list_select_contact.setAdapter(new SimpleAdapter(this, data,
R.layout.contact_item_view, new String[] { "name", "phone" },
new int[] { R.id.tv_name, R.id.tv_phone }));
}
/**
* 读取手里面的联系人
*
* @return
*/
private List<Map<String, String>> getContactInfo() {
//把所有的联系人
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
// 得到一个内容解析器
ContentResolver resolver = getContentResolver();
// raw_contacts uri
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri uriData = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, new String[] { "contact_id" },
null, null, null);
while (cursor.moveToNext()) {
String contact_id = cursor.getString(0);
if (contact_id != null) {
//具体的某一个联系人
Map<String, String> map = new HashMap<String, String>();
Cursor dataCursor = resolver.query(uriData, new String[] {
"data1", "mimetype" }, "contact_id=?",
new String[] { contact_id }, null);
while (dataCursor.moveToNext()) {
String data1 = dataCursor.getString(0);
String mimetype = dataCursor.getString(1);
System.out.println("data1=="+data1+"==mimetype=="+mimetype);
if("vnd.android.cursor.item/name".equals(mimetype)){
//联系人的姓名
map.put("name", data1);
}else if("vnd.android.cursor.item/phone_v2".equals(mimetype)){
//联系人的电话号码
map.put("phone", data1);
}
}
list.add(map);
dataCursor.close();
}
}
cursor.close();
return list;
}
}
6.设置安全号码
(1)把数据回传上一个Activity
public void selectContact(View view){
Intent intent = new Intent(this,SelectContactActivity.class);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(data == null)
return;
String phone = data.getStringExtra("phone").replace("-", "");
et_setup3_phone.setText(phone);
}
下一个Activity
Intent data = new Intent();
data.putExtra("phone", phone);
setResult(0, data);
//当前页面关闭掉
finish();
7.手机防盗的核心原理
(0)发送信息权限
<uses-permission android:name="android.permission.SEND_SMS"/>
(1)开机后发现sim卡发生改变就发送信息(监听器:BootCompleteReceiver中)
System.out.println("sim卡变更了,需要偷偷发短信;");
String safenumber = sp.getString("safenumber", "");
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(safenumber, null, "sim card change !", null, null);
(2)
manager.sendTextMessage(mobile,null,text,null,null);
//第一个参数:对方手机号码
//第二个参数:短信中心号码,一般设置为空
//第三个参数:短信内容
//第四个参数:sentIntent判断短信是否发送成功,如果你没有SIM卡,或者网络中断,则可以通过这个intent来判断。
//注意强调的是“发送”的动作是否成功。那么至于对于对方是否收到,另当别论
//第五个参数:当短信发送到收件人时,会收到这个deliveryIntent。即强调了“发送”后的结果
//就是说是在"短信发送成功"和"对方收到此短信"才会激活sentIntent和deliveryIntent这两个Intent。这也相当于是延迟执行了Intent
8.短信指令的广播接受者
(0)接收短信需要权限
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
(1)接收安全号码发来的短信 (2)广播接收者需要配置
eceiver android:name="com.itheima.mobilesafe.receiver.SMSReceiver" android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
(3)把这个广播终止掉: 提高优先级+abortBroadcast(); (4)代码
public class SMSReceiver extends BroadcastReceiver {
private static final String TAG = "SMSReceiver";
private SharedPreferences sp;
@Override
public void onReceive(Context context, Intent intent) {
// 写接收短信的代码
Object[] objs = (Object[]) intent.getExtras().get("pdus");
sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
for(Object b:objs){
//具体的某一条短信
SmsMessage sms =SmsMessage.createFromPdu((byte[]) b);
//发送者
String sender = sms.getOriginatingAddress();//15555555556,信息发送者
String safenumber = sp.getString("safenumber", "");//5556,获取保存的安全号码
// Toast.makeText(context, sender, 1).show();
String body = sms.getMessageBody();//信息内容
if(sender.equals(safenumber)){
if("#*location*#".equals(body)){
//得到手机的GPS
Log.i(TAG, "得到手机的GPS");
//把这个广播终止掉
abortBroadcast();
}else if("#*alarm*#".equals(body)){
//播放报警影音
Log.i(TAG, "播放报警影音");
abortBroadcast();
}
else if("#*wipedata*#".equals(body)){
//远程清除数据
Log.i(TAG, "远程清除数据");
abortBroadcast();
}
else if("#*lockscreen*#".equals(body)){
//远程锁屏
Log.i(TAG, "远程锁屏");
abortBroadcast();
}
}
}
}
}
9.播放报警音乐
(1) 音频资源:res目录下创建raw文件夹,再放音频资源 (2)代码
MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
player.setLooping(false);//是否循环
player.setVolume(1.0f, 1.0f);//音量
player.start();
10.三种获取手机的位置的方式
(1)网络定位(network):
前提是必须连上网络:wifi、3G、2G;
获取到IP地址 ----------查网络上的ip数据库
有局限性:针对固定的IP地址。
如果手机网或者ip地址是动态分布IP,这个偏差就很大。这种情况是无法满足需求的。
(2) 基站定位( passive )
工作原理:手机能打电话,是需要基站的。手机定位也是用基站的。
手机附近能收到3个基站的信号,就可以定位了。
基站定位有可能很准确,比如基站多的地方;
如果基站少的话就会相差很大。
(3) GPS 定位 (gps)
GPS:不需要网络
A-GPS:使用了卫星定位 需要联网辅助修正位置,精确度15米左右
11.代码实现获取手机位置
(1)权限 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>----------获取精确位置
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>--------获取粗略位置
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>----------模拟器开发需要
(2)GPSDemo------例子代码
public class MainActivity extends Activity {
// 用到位置服务
private LocationManager lm;
private MyLocationListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
//List<String> provider = lm.getAllProviders(); //三种方式
//for(String l: provider){
// System.out.println(l);
//}
listener = new MyLocationListener();
//注册监听位置服务
Criteria criteria = new Criteria(); //定位的条件,给位置提供者设置条件,选出最好的方式
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//设置参数细化:
//criteria.setAccuracy(Criteria.ACCURACY_FINE);//设置为最大精度
//criteria.setAltitudeRequired(false);//不要求海拔信息
//criteria.setBearingRequired(false);//不要求方位信息
//criteria.setCostAllowed(true);//是否允许付费
//criteria.setPowerRequirement(Criteria.POWER_LOW);//对电量的要求
String proveder= lm.getBestProvider(criteria, true); //定位有三种方式,得到最好的
lm.requestLocationUpdates(proveder, 0, 0, listener);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// 取消监听位置服务
lm.removeUpdates(listener);
listener = null;
}
class MyLocationListener implements LocationListener {
/**
* 当位置改变的时候回调
*/
@Override
public void onLocationChanged(Location location) {
String longitude = "经度:" + location.getLongitude();
String latitude = "纬度:" + location.getLatitude();
String accuracy = "精确度:" + location.getAccuracy();
TextView textview = new TextView(MainActivity.this);
textview.setText(longitude + "\n" + latitude + "\n" + accuracy);
setContentView(textview);
}
/**
* 当状态发生改变的时候回调 开启--关闭 ;关闭--开启
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
/**
* 某一个位置提供者可以使用了
*/
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
/**
* 某一个位置提供者不可以使用了
*/
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
(3)火星坐标系统:人为加偏坐标,国家安全 火星坐标转换代码 使用网上已有的代码和数据库 HuoXingDemo-------代码例子 a. 把数据库导入工程里(数据库名:axisoffset.dat) b. ModifyOffset.java-------------已有类,网上下载
import java.io.InputStream;
import java.io.ObjectInputStream;
/**
* 火星地球坐标转化.地图坐标修偏
*
*/
public class ModifyOffset {
private static ModifyOffset modifyOffset;
static double[] X = new double[660 * 450];
static double[] Y = new double[660 * 450];
private ModifyOffset(InputStream inputStream) throws Exception {
init(inputStream);
}
public synchronized static ModifyOffset getInstance(InputStream is) throws Exception {
if (modifyOffset == null) {
modifyOffset = new ModifyOffset(is);
}
return modifyOffset;
}
public void init(InputStream inputStream) throws Exception {
ObjectInputStream in = new ObjectInputStream(inputStream);
try {
int i = 0;
while (in.available() > 0) {
if ((i & 1) == 1) {
Y[(i - 1) >> 1] = in.readInt() / 100000.0d;
;
} else {
X[i >> 1] = in.readInt() / 100000.0d;
;
}
i++;
}
} finally {
if (in != null)
in.close();
}
}
// standard -> china
public PointDouble s2c(PointDouble pt) {
int cnt = 10;
double x = pt.x, y = pt.y;
while (cnt-- > 0) {
if (x < 71.9989d || x > 137.8998d || y < 9.9997d || y > 54.8996d)
return pt;
int ix = (int) (10.0d * (x - 72.0d));
int iy = (int) (10.0d * (y - 10.0d));
double dx = (x - 72.0d - 0.1d * ix) * 10.0d;
double dy = (y - 10.0d - 0.1d * iy) * 10.0d;
x = (x + pt.x + (1.0d - dx) * (1.0d - dy) * X[ix + 660 * iy] + dx
* (1.0d - dy) * X[ix + 660 * iy + 1] + dx * dy
* X[ix + 660 * iy + 661] + (1.0d - dx) * dy
* X[ix + 660 * iy + 660] - x) / 2.0d;
y = (y + pt.y + (1.0d - dx) * (1.0d - dy) * Y[ix + 660 * iy] + dx
* (1.0d - dy) * Y[ix + 660 * iy + 1] + dx * dy
* Y[ix + 660 * iy + 661] + (1.0d - dx) * dy
* Y[ix + 660 * iy + 660] - y) / 2.0d;
}
return new PointDouble(x, y);
}
// china -> standard
public PointDouble c2s(PointDouble pt) {
int cnt = 10;
double x = pt.x, y = pt.y;
while (cnt-- > 0) {
if (x < 71.9989d || x > 137.8998d || y < 9.9997d || y > 54.8996d)
return pt;
int ix = (int) (10.0d * (x - 72.0d));
int iy = (int) (10.0d * (y - 10.0d));
double dx = (x - 72.0d - 0.1d * ix) * 10.0d;
double dy = (y - 10.0d - 0.1d * iy) * 10.0d;
x = (x + pt.x - (1.0d - dx) * (1.0d - dy) * X[ix + 660 * iy] - dx
* (1.0d - dy) * X[ix + 660 * iy + 1] - dx * dy
* X[ix + 660 * iy + 661] - (1.0d - dx) * dy
* X[ix + 660 * iy + 660] + x) / 2.0d;
y = (y + pt.y - (1.0d - dx) * (1.0d - dy) * Y[ix + 660 * iy] - dx
* (1.0d - dy) * Y[ix + 660 * iy + 1] - dx * dy
* Y[ix + 660 * iy + 661] - (1.0d - dx) * dy
* Y[ix + 660 * iy + 660] + y) / 2.0d;
}
return new PointDouble(x, y);
}
}
class PointDouble {
double x, y;
PointDouble(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return "x=" + x + ", y=" + y;
}
}
c.使用
public class Demo {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ModifyOffset offset = ModifyOffset.getInstance(Demo.class.getResourceAsStream("axisoffset.dat"));
PointDouble newdouble1 = offset.s2c(new PointDouble(116.29042787, 40.04337062));
System.out.println(newdouble1);
}
}
12.移植GPS代码
0.权限 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>----------获取精确位置
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>--------获取粗略位置
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>----------模拟器开发需要
1.数据库放在工程assets目录下 1.使用服务监听------没有界面 2.服务需要在功能清单中配置 <service android:name="com.itheima.mobilesafe.service.GPSService"/> 3.火星地球坐标转化.地图坐标修偏(与服务放在同一个包里)-----------工具类
/**
* 火星地球坐标转化.地图坐标修偏
*
*/
public class ModifyOffset {
private static ModifyOffset modifyOffset;
static double[] X = new double[660 * 450];
static double[] Y = new double[660 * 450];
private ModifyOffset(InputStream inputStream) throws Exception {
init(inputStream);
}
public synchronized static ModifyOffset getInstance(InputStream is) throws Exception {
if (modifyOffset == null) {
modifyOffset = new ModifyOffset(is);
}
return modifyOffset;
}
public void init(InputStream inputStream) throws Exception {
ObjectInputStream in = new ObjectInputStream(inputStream);
try {
int i = 0;
while (in.available() > 0) {
if ((i & 1) == 1) {
Y[(i - 1) >> 1] = in.readInt() / 100000.0d;
;
} else {
X[i >> 1] = in.readInt() / 100000.0d;
;
}
i++;
}
} finally {
if (in != null)
in.close();
}
}
// standard -> china
public PointDouble s2c(PointDouble pt) {
int cnt = 10;
double x = pt.x, y = pt.y;
while (cnt-- > 0) {
if (x < 71.9989d || x > 137.8998d || y < 9.9997d || y > 54.8996d)
return pt;
int ix = (int) (10.0d * (x - 72.0d));
int iy = (int) (10.0d * (y - 10.0d));
double dx = (x - 72.0d - 0.1d * ix) * 10.0d;
double dy = (y - 10.0d - 0.1d * iy) * 10.0d;
x = (x + pt.x + (1.0d - dx) * (1.0d - dy) * X[ix + 660 * iy] + dx
* (1.0d - dy) * X[ix + 660 * iy + 1] + dx * dy
* X[ix + 660 * iy + 661] + (1.0d - dx) * dy
* X[ix + 660 * iy + 660] - x) / 2.0d;
y = (y + pt.y + (1.0d - dx) * (1.0d - dy) * Y[ix + 660 * iy] + dx
* (1.0d - dy) * Y[ix + 660 * iy + 1] + dx * dy
* Y[ix + 660 * iy + 661] + (1.0d - dx) * dy
* Y[ix + 660 * iy + 660] - y) / 2.0d;
}
return new PointDouble(x, y);
}
// china -> standard
public PointDouble c2s(PointDouble pt) {
int cnt = 10;
double x = pt.x, y = pt.y;
while (cnt-- > 0) {
if (x < 71.9989d || x > 137.8998d || y < 9.9997d || y > 54.8996d)
return pt;
int ix = (int) (10.0d * (x - 72.0d));
int iy = (int) (10.0d * (y - 10.0d));
double dx = (x - 72.0d - 0.1d * ix) * 10.0d;
double dy = (y - 10.0d - 0.1d * iy) * 10.0d;
x = (x + pt.x - (1.0d - dx) * (1.0d - dy) * X[ix + 660 * iy] - dx
* (1.0d - dy) * X[ix + 660 * iy + 1] - dx * dy
* X[ix + 660 * iy + 661] - (1.0d - dx) * dy
* X[ix + 660 * iy + 660] + x) / 2.0d;
y = (y + pt.y - (1.0d - dx) * (1.0d - dy) * Y[ix + 660 * iy] - dx
* (1.0d - dy) * Y[ix + 660 * iy + 1] - dx * dy
* Y[ix + 660 * iy + 661] - (1.0d - dx) * dy
* Y[ix + 660 * iy + 660] + y) / 2.0d;
}
return new PointDouble(x, y);
}
}
class PointDouble {
double x, y;
PointDouble(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return "x=" + x + ", y=" + y;
}
}
(4)服务类 GPSService
public class GPSService extends Service {
// 用到位置服务
private LocationManager lm;
private MyLocationListener listener;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// List<String> provider = lm.getAllProviders();
// for(String l: provider){
// System.out.println(l);
// }
listener = new MyLocationListener();
// 注册监听位置服务
// 给位置提供者设置条件
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// 设置参数细化:
// criteria.setAccuracy(Criteria.ACCURACY_FINE);//设置为最大精度
// criteria.setAltitudeRequired(false);//不要求海拔信息
// criteria.setBearingRequired(false);//不要求方位信息
// criteria.setCostAllowed(true);//是否允许付费
// criteria.setPowerRequirement(Criteria.POWER_LOW);//对电量的要求
String proveder = lm.getBestProvider(criteria, true);
lm.requestLocationUpdates(proveder, 0, 0, listener);
}
@Override
public void onDestroy() {
super.onDestroy();
// 取消监听位置服务
lm.removeUpdates(listener);
listener = null;
}
class MyLocationListener implements LocationListener {
/**
* 当位置改变的时候回调
*/
@Override
public void onLocationChanged(Location location) {
String longitude = "j:" + location.getLongitude() + "\n";
String latitude = "w:" + location.getLatitude() + "\n";
String accuracy = "a" + location.getAccuracy() + "\n";
// 发短信给安全号码
// 把标准的GPS坐标转换成火星坐标
// InputStream is;
// try {
// is = getAssets().open("axisoffset.dat");
// ModifyOffset offset = ModifyOffset.getInstance(is);
// PointDouble double1 = offset.s2c(new PointDouble(location
// .getLongitude(), location.getLatitude()));
// longitude ="j:" + offset.X+ "\n";
// latitude = "w:" +offset.Y+ "\n";
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("lastlocation", longitude + latitude + accuracy);
editor.commit();
}
/**
* 当状态发生改变的时候回调 开启--关闭 ;关闭--开启
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
/**
* 某一个位置提供者可以使用了
*/
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
/**
* 某一个位置提供者不可以使用了
*/
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
13.一键锁屏&清除数据
API:Device Policies (1)一键锁屏-------Demo a: 创建一个类继承DeviceAdminReceiver
/**
* 特殊的广播接收者
* @author Administrator
*
*/
public class MyAdmin extends DeviceAdminReceiver {
}
b.功能清单中注册
<receiver
android:name="com.itheima.lockscreen.MyAdmin"
android:description="@string/sample_device_admin_description" <-用户管理员的描述信息->
android:label="@string/sample_device_admin" <-设置管理员权限->
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>
c.在res目录下创建xml文件夹再创建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>
d.主代码(一键锁屏&删除数据,恢复出厂)
public class MainActivity extends Activity {
/**
* 设备策略服务
*/
private DevicePolicyManager dpm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
}
/**
* 用代码去开启管理员
* @param view
*/
public void openAdmin(View view){
//创建一个Intent
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);
}
/**
* 一键锁屏
*/
public void lockscreen(View view){
ComponentName who = new ComponentName(this,MyAdmin.class);
if(dpm.isAdminActive(who)){
dpm.lockNow();//锁屏
dpm.resetPassword("", 0);//设置屏蔽密码
//清除Sdcard上的数据
// dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
//恢复出厂设置
// dpm.wipeData(0);
}else{
Toast.makeText(this, "还没有打开管理员权限", 1).show();
return ;
}
}
/**
* 卸载当前软件
*/
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.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse("package:"+getPackageName()));
startActivity(intent);
}
}