This project is a more interesting project source code, can give other items to lock, the principle of the program is a "watchdog" service regularly monitor top-level activity, if the activity corresponding to the package name is locked before the application, then a page will require the input unlock password.
The effect is as follows:
1. Basic Ideas
①. Create a database with a locked application (field: _id,packagename), and if the application is locked, maintain the lock-applied package name into the database
②. Lock + unlocked = All applications in mobile phone (appinfoprovider)
2. Locked and unlocked data adapters
Class Myadapter extends baseadapter{private Boolean islock; /** * @param islock is used to differentiate between locked and unlocked applications. Lock data adapter False Unlocked data adapter */Public Myadapter (Boolean islock) {This.islock = is
Lock;
@Override public int GetCount () {if (Islock) {Tv_lock.settext ("Lock Applied:" +mlocklist.size ());
return Mlocklist.size ();
}else{Tv_unlock.settext ("Unlocked Application:" +munlocklist.size ());
return Munlocklist.size ();
@Override public AppInfo getitem (int position) {if (Islock) {return mlocklist.get (position);
}else{return Munlocklist.get (position);
@Override public long getitemid (int position) {return position;
@Override public View getview (int position, View Convertview, ViewGroup parent) {Viewholder holder = null;
if (Convertview = = null) {Convertview = View.inflate (Getapplicationcontext (), r.layout.listview_islock_item, NULL);
Holder = new Viewholder ();
Holder.iv_icon = (ImageView) Convertview.findviewbyid (R.id.iv_icon); Holder.tv_name = (TextView) CONVERTVIEw.findviewbyid (R.id.tv_name);
Holder.iv_lock = (ImageView) Convertview.findviewbyid (R.id.iv_lock);
Convertview.settag (holder);
}else{holder = (viewholder) convertview.gettag ();
Final AppInfo AppInfo = getitem (position);
Final View Animationview = Convertview;
Holder.iv_icon.setBackgroundDrawable (Appinfo.icon);
Holder.tv_name.setText (Appinfo.name);
if (islock) {holder.iv_lock.setBackgroundResource (r.drawable.lock);
}else{Holder.iv_lock.setBackgroundResource (R.drawable.unlock); Holder.iv_lock.setOnClickListener (New Onclicklistener () {@Override public void OnClick (View v) {//Add animation effect, animation default right and wrong Blocked, so the animation of the same time, the following code will also execute Animationview.startanimation (mtranslateanimation),//500 MS//Animation execution process to do event monitoring, after hearing the animation execution, Then remove the data from the collection, manipulate the database, and refresh the interface Mtranslateanimation.setanimationlistener (new Animationlistener () {@Override public void OnA Nimationstart (Animation Animation) {//animation starts by calling the method} @Override public void Onanimationrepeat (Animation animatio N) {//moveThe method is called when the drawing is repeated @Override public void Onanimationend (Animation Animation) {if (Islock) {//locked) after the animation execution is completed
------> Unlocked Process//1. A lock collection is deleted, an unlocked collection is added, and an object is an object that GetItem method obtains Mlocklist.remove (AppInfo);
Munlocklist.add (AppInfo);
2. Delete a data mdao.delete (Appinfo.packagename) from the locked database;
3. Refresh data adapter mlockadapter.notifydatasetchanged ();
}else{//UNLOCKED------> Locked process//1. The lock collection has been added one, and the lock set is removed, and the object is the object Mlocklist.add (AppInfo) that the GetItem method obtains;
Munlocklist.remove (AppInfo);
2. Insert a data Mdao.insert (Appinfo.packagename) from the locked database;
3. Refresh data adapter munlockadapter.notifydatasetchanged ();
}
}
});
}
});
return convertview;
}
}
Mlockadapter = new Myadapter (true);
Lv_lock.setadapter (mlockadapter);
Munlockadapter = new Myadapter (false);
Lv_unlock.setadapter (Munlockadapter);
3. Locked and unlocked item click event Handling
Holder.iv_lock.setOnClickListener (New Onclicklistener () {@Override public void OnClick (View v) {//Add animation effect, animation default is Non-blocking, To perform the animation, the following code also executes Animationview.startanimation (mtranslateanimation),//500 milliseconds//performs event monitoring on the animation execution, and after the execution of the animation is heard, Then remove the data from the collection, manipulate the database, and refresh the interface Mtranslateanimation.setanimationlistener (new Animationlistener () {@Override public void Onanim
Ationstart (Animation Animation) {//animation starts with calling method} @Override public void Onanimationrepeat (Animation Animation) { Call method when animation is repeated @Override public void Onanimationend (Animation Animation) {if (Islock) {//Locked---
---> Unlocked process//1. A lock collection is deleted, an unlocked collection is added, and an object is an object that GetItem method obtains Mlocklist.remove (AppInfo);
Munlocklist.add (AppInfo);
2. Delete a data mdao.delete (Appinfo.packagename) from the locked database;
3. Refresh data adapter mlockadapter.notifydatasetchanged ();
}else{//UNLOCKED------> Locked process//1. The lock collection has been added one, and the lock set is removed, and the object is the object Mlocklist.add (AppInfo) that the GetItem method obtains;
Munlocklist.remove (AppInfo); 2. Insert a piece of data from the locked database mdao.insERT (Appinfo.packagename);
3. Refresh data adapter munlockadapter.notifydatasetchanged ();
}
}
});
}
});
4. The program lock must be maintained in the service
① Basic Ideas
- Determine the current open application (now mobile phone visible task stack)
- If the open application is in the locked list, eject the blocking interface
- Watchdog service, has been (dead loop (child thread, controllable) to open the application to do the listening
public class Watchdogservice extends Service {private Boolean iswatch;
Private Applockdao Mdao;
Private list<string> mpacknamelist;
Private Innerreceiver Minnerreceiver;
Private String Mskippackagename;
Private Mycontentobserver Mcontentobserver;
@Override public void OnCreate () {//maintains a watchdog's dead loop, allowing it to monitor the application now open for application Mdao = Applockdao.getinstance (this) to be intercepted in the program lock;
Iswatch = true;
Watch ();
Intentfilter intentfilter = new Intentfilter ();
Intentfilter.addaction ("Android.intent.action.SKIP");
Minnerreceiver = new Innerreceiver ();
Registerreceiver (Minnerreceiver, Intentfilter);
Register a content Watcher, observe the changes in the database, and once the data has been deleted or added, you need to let mpacknamelist retrieve the data again Mcontentobserver = new Mycontentobserver (new Handler ());
Getcontentresolver (). Registercontentobserver (Uri.parse ("Content://applock/change"), true, Mcontentobserver);
Super.oncreate ();
Class Mycontentobserver extends contentobserver{public mycontentobserver (Handler Handler) {super (Handler); ///Once the database has changed, call the methodTo retrieve the data for the collection that contains the package name @Override public void OnChange (Boolean selfchange) {new Thread () {public void run () {Mpacknameli
st = Mdao.findall ();
};
}.start ();
Super.onchange (Selfchange);
Class Innerreceiver extends broadcastreceiver{@Override public void onreceive (context context, Intent Intent) {
Gets the package name passed over during the sending broadcast, skips the Mskippackagename = Intent.getstringextra ("PackageName") in the packet name detection process;
}} private void Watch () {//1, child thread, open a controllable loop new thread () {public void run () {mpacknamelist = Mdao.findall (); while (Iswatch) {//2. Monitoring now open applications, task stack//3. Get Activity Manager Object Activitymanager am = (activitymanager) getsystemservice
(Context.activity_service);
4. Get the task stack list<runningtaskinfo> runningtasks = am.getrunningtasks (1) that is opening the application;
Runningtaskinfo runningtaskinfo = runningtasks.get (0);
5. Gets the activity at the top of the stack, and then the package name String PackageName = RunningTaskInfo.topActivity.getPackageName () that is applied to the activity where it is obtained; If the task stack points to an application with a switch, the empty string//6 is mskippackagename. Take this package name in the addedLock package name in the collection, if you include the secondary package name, you need to eject the Intercept interface if (Mpacknamelist.contains (PackageName)) {//If the program now detected, and unlocked, you do not need to eject the blocking interface if (!packagen Ame.equals (Mskippackagename)) {//7, pop-up blocking interface Intent Intent = new Intent (Getapplicationcontext (), Enterpsdactivity.clas
s);
Intent.setflags (Intent.flag_activity_new_task);
Intent.putextra ("PackageName", PackageName);
StartActivity (Intent);
}///Sleep, time slice rotation try {thread.sleep (500);
catch (Interruptedexception e) {e.printstacktrace ();
}
}
};
}.start ();
@Override public IBinder onbind (Intent arg0) {return null;
@Override public void OnDestroy () {//stop watchdog loop Iswatch = false;
Cancellation of Broadcast recipient if (Minnerreceiver!=null) {unregisterreceiver (minnerreceiver);
}//Logoff content observer if (mcontentobserver!=null) {getcontentresolver (). Unregistercontentobserver (Mcontentobserver);
} Super.ondestroy ();
}
}
public class Enterpsdactivity extends activity {private String packagename;
Private TextView Tv_app_name;
Private ImageView Iv_app_icon;
Private EditText ET_PSD;
Private Button Bt_submit;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Gets the package name PackageName = Getintent (). Getstringextra ("PackageName");
Setcontentview (R.LAYOUT.ACTIVITY_ENTER_PSD);
Initui ();
InitData ();
private void InitData () {//Gets the icon to intercept the application and the name Packagemanager pm = Getpackagemanager () by passing the package name.
try {applicationinfo applicationinfo = Pm.getapplicationinfo (packagename,0);
drawable icon = Applicationinfo.loadicon (PM);
Iv_app_icon.setbackgrounddrawable (icon);
Tv_app_name.settext (Applicationinfo.loadlabel (PM). toString ());
catch (Namenotfoundexception e) {e.printstacktrace (); Bt_submit.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {String psd = Et_ps
D.gettext (). toString (); if (! Textutils.isempty(PSD)) {if (Psd.equals ("123")) {//unlock, enter application, tell the door not to listen and unlock the application, send the broadcast Intent Intent = new Intent ("Android.intent.action.SKIP
");
Intent.putextra ("PackageName", PackageName);
Sendbroadcast (Intent);
Finish ();
}else{toastutil.show (Getapplicationcontext (), "wrong password");
}}else{Toastutil.show (Getapplicationcontext (), "Please enter password");
}
}
});
private void Initui () {tv_app_name = (TextView) Findviewbyid (r.id.tv_app_name);
Iv_app_icon = (ImageView) Findviewbyid (R.id.iv_app_icon);
ET_PSD = (edittext) Findviewbyid (R.ID.ET_PSD);
Bt_submit = (Button) Findviewbyid (r.id.bt_submit);
@Override public void onbackpressed () {//through implicit intent, jumps to the desktop Intent Intent = new Intent (intent.action_main);
Intent.addcategory (Intent.category_home);
StartActivity (Intent);
Super.onbackpressed ();
}
}
5. Hide recently opened activity
<activity
android:excludefromrecents= "true"
android:name= "com.itheima.mobilesafe.EnterPwdActivity"
android:launchmode= "SingleInstance"/>
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.