Lipo teaches you how to implement one-click lock screen software for Android

Source: Internet
Author: User

In the past few days, I feel that I need to build a software that I need to lock the screen. If I don't have any good options, I just need to do it myself. If I do this, I will enjoy the advantages of technology and self-reliance.

First:

This figure briefly lists the features:

[1] display of date and time

[2] display of power and battery status

[3] switching of background images

[4] A small lock image. After clicking it, the screen will be locked in 5 seconds.

[5] sliding to the right ends the screen lock animation effect. The green ball slides to the Right to unlock the screen.

For the above five features, I will focus on [4]. I will briefly discuss the implementation ideas for others.

[1] Date and Time display:

You can use textview to implement the two functions. Note that the handler of the update date only needs to be updated once every minute. The excessive refresh frequency seriously affects the battery consumption of the mobile phone. I can see someone using digitalclock, after testing, the power consumption is too large, which is not a good solution;

[2] display of power and battery status:

For power updates, you must use alarmmanager to periodically and continuously send battery information.

Intent alarmintent = new intent (); alarmintent = intent; pendingintent = pendingintent. getservice (this, 0, alarmintent, 0); alarmmanager alarm = (alarmmanager) getsystemservice (context. alarm_service); alarm. set (alarmmanager. rtc_wakeup, define a cycle time, pendingintent );

Then, you need to define one broadcastreceiver,

/** Define a broascastreceiver */private broadcastreceiver batteryreceiver = new broadcastreceiver () {@ overridepublic void onreceive (context, intent) {currentbatterylevel = intent. getintextra ("level", 0); currentbatterystatus = intent. getintextra ("status", 0); currentbatteryplugged = intent. getintextra ("plugged", 0 );}};

For the rest, you can find some battery pictures corresponding to different power values.

[3] switching of background images

I don't think it is necessary to start a thread to do this. After all, I am doing this in onattachedtowindow () of the main activity on the principle of consuming less resources,

By default, five images are displayed in the app, which can be displayed randomly. Of course, you want to expand the following functions: for example, it is also good to allow users to switch from the photos.

[4] A small lock image. After clicking it, the screen will be locked in 5 seconds.

I have seen a lot of "one-click lock" software that is used to lock the screen immediately after clicking it. Of course, I personally prefer to enter the software of a lock entity so that users can use more selective functions;

This feature is not difficult, but you need to consider the following:

Devicepolicymanager mdpm = (devicepolicymanager) getsystemservice (context. device_policy_service );

Mdpm. locknow ();

There are only two lines of code. Can I really lock the screen? Of course not.

Componentname mlockscreenadmin = new componentname (this, lock. Class );

If (mdpm. isadminactive (mlockscreenadmin )){

Mdpm. locknow ();

}

In this way, the lock must be extends deviceadminreceiver.

In androidmantifest. XML, You need to configure the lock handler:

<! -- Lock screen service listening, must be added --> <javaser Android: Label = "souapp_screenlockmanager" Android: Name = ". lock "Android: Permission =" android. permission. bind_device_admin "Android: Description =" @ string/about "> <meta-data Android: Name =" android. app. device_admin "Android: Resource =" @ XML/lock_screen_admin "/> <intent-filter> <action Android: Name =" android. app. action. device_admin_enabled "/> </intent-filter> </er ER>

Create a lock_screen_admin.xml file in the Res/XML directory.

<?xml version="1.0" encoding="UTF-8"?><device-admin  xmlns:android="http://schemas.android.com/apk/res/android">    <uses-policies>        <force-lock />    </uses-policies></device-admin>

[5] sliding to the right ends the screen lock animation effect. The green ball slides to the Right to unlock the screen.

You can customize a view: maskedtextview. The source code is as follows:

public class MaskedTextView extends View{        private Paint txtPaint;    private Shader shader;    private float dx=50;    private long lastTime = System.currentTimeMillis();    private boolean start = false;            private void init(){        txtPaint = new Paint();        txtPaint.setColor(Color.GRAY);        txtPaint.setAntiAlias(true);        txtPaint.setTextSize(26);        shader = new LinearGradient(0, 0, 200, 0,                new int[]{Color.argb(255, 120, 120, 120), Color.argb(255, 120, 120, 120), Color.WHITE}, new float[]{0, 0.7f, 1}, TileMode.MIRROR);        txtPaint.setShader(shader);    }        public MaskedTextView(Context context) {                super(context);        init();    }        public MaskedTextView(Context context, AttributeSet attrs){        super(context, attrs);        init();    }        public void setStart(boolean start) {        this.start = start;        invalidate();    }            @Override    protected void onDraw(Canvas canvas) {        long now = System.currentTimeMillis();        float elapsed = (now - lastTime)/4.5f;        dx += elapsed;        Matrix matrix = new Matrix();        if(start){            matrix.setTranslate(dx, 0);            invalidate();        }else{            matrix.setTranslate(0, 0);        }        shader.setLocalMatrix(matrix);        canvas.drawText(getContext().getString(R.string.hint_unlock), 0, 25, txtPaint);        lastTime = now;    }    }

The animation about dragging and unlocking a ball is actually to write a sliderrelativelayout by yourself, which loads the ball and unlock the box. When the ball slides to the right, you can determine whether it has reached the unlock position, if the unlock position is exceeded, unlock the video. Otherwise, play the animation returned by the ball.

Other minor problems:

[Full screen display at the beginning of the main activity, and the notification bar appears after unlocking]

Even if you set a full-screen flag in oncreate or onresume, the screen Lock shields the Home Key.

Getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen,
Windowmanager. layoutparams. flag_fullscreen );

Add the code for shielding the Home Key in the onattachedtowindow () method of the main activity:

This. getwindow (). settype (windowmanager. layoutparams. type_keyguard_dialog );

Solution: Set the full-screen flag only once before the Home Key is blocked. The complete code is as follows:

Public void onattachedtowindow () {// set full screen mode getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); updatebackgroundwallper (); // change the background this. getwindow (). settype (windowmanager. layoutparams. type_keyguard_dialog); super. onattachedtowindow ();}

Android about sleep a few pitfalls: can refer to this article http://www.whoslab.me/blog? P = 474

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.