1. 程式人生 > >android PowerManager亮滅屏(實現篇)

android PowerManager亮滅屏(實現篇)

網上查了好多資料 不是講原理就是講原理呀! 你Tm到是實現呀!!!墨跡一大篇文章,都是看的官文件然後加上自己的理解一頓墨跡。

具體講下我要實現的功能:

Android 6.0實現自動亮滅螢幕,按下電源鍵螢幕滅屏5s後自動亮屏,時間可以自己設定

用到的知識有 1:powermanger的基礎知識  

 2:超級管理員許可權  重中之重呀!!!!

參考超級管理員連結點選開啟連結

 3:Handler的基礎知識

 4:BroadcastReceiver的廣播通知的基礎知識

 5:基礎知識相信大家找網上一大堆

 6:基礎連結我就不給大家發了  相信你們比我找的好

 據說4.0以後為了安全,谷歌兄做了很多安全設施。power電池管理就很難搞了,整了一週費勁巴力的弄了出來

廢話不多說了直接上程式碼。 放心程式碼一定要全部。

首先是MainActivity 的程式碼

package com.example.unruly_zhao.powermanager_wakelock;


import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener {


    private Button startBtn = null;
    private Button stopBtn = null;


    private EditText timeEditText = null;
    private EditText delayEditText = null;

    private TextView textviewResult = null;
    private TextView textviewVersion = null;


    /**
     * 裝置管理
     */
    public DevicePolicyManager mDPM;
    /**
     * 次數
     */
    int time;
    /**
     * 延遲時間
     */
    int delay;
    /**
     * 計數
     */
    int timeCount;
    /**
     * 中間數
     */
    int timemid;


    /**
     * 元件
     */
    ComponentName devAdmReceiver;


    protected String tag = getClass().getSimpleName();


    protected static final int REQUEST_ENABLE = 0;


    protected static final int GUI_DOING = 0;
    protected static final int GUI_FINISH = 1;


    private KeyguardManager km;
    private KeyguardLock kl;
    private PowerManager pm;
    private PowerManager.WakeLock wl;


    LockScreen lockScreen = new LockScreen();

    int sucCount;
    int failCount;

    String versionName = "2016_10_14_WakeUp_1.0";


    /**
     * handler  deal with msg
     */
    Handler handler = new Handler() {


        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GUI_DOING:
                    Log.e(tag, "doing-->執行");
                    String string = (String) msg.obj;
                    textviewResult.setText(string);
                    textviewResult.setGravity(Gravity.CENTER);
                    break;
                case GUI_FINISH:
                    Log.e(tag, "doing-->完成");
                    String string1 = (String) msg.obj;
                    textviewResult.setText(string1);
                    textviewResult.setGravity(Gravity.CENTER);
                    break;

                default:
                    break;
            }


        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mBatInfoReceiver, filter);

        Log.e(tag, "wake up oncreate");
        init();

    }

    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if(Intent.ACTION_SCREEN_ON.equals(action)){
                Log.d("lyj", "-----------------screen is on...");
            }else if(Intent.ACTION_SCREEN_OFF.equals(action)){
                Log.d("lyj", "----------------- screen is off...");

                handler.postDelayed(wakelockRunnable, 1000);
            }
        }

    };


    /**
     * init初始化
     */
    private void init() {
// TODO Auto-generated method stub
        this.startBtn = (Button) findViewById(R.id.button1);
        startBtn.setOnClickListener(this);


        this.stopBtn = (Button) findViewById(R.id.button2);
        stopBtn.setOnClickListener(this);
        stopBtn.setEnabled(false);


        this.timeEditText = (EditText) findViewById(R.id._time);
        timeEditText.setText("1");
        timeEditText.setGravity(Gravity.CENTER);


        this.delayEditText = (EditText) findViewById(R.id.jiangeshuzi);
        delayEditText.setText("3");
        delayEditText.setGravity(Gravity.CENTER);


        this.textviewResult = (TextView) findViewById(R.id.ttextviewResult);
        this.textviewVersion = (TextView) findViewById(R.id.textView2);
        textviewVersion.setTextColor(Color.RED);
// textviewVersion.setText("2016-9-30_QKLabTestV1.0");
        textviewVersion.setText(versionName);

        Log.e(tag, "wake up init");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
        if (REQUEST_ENABLE == requestCode) {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    /**
     * 喚醒 解鎖
     */
    private void wakeAndUnlock(boolean b) {
        if (b) {
// 獲取電源管理器物件
            pm = (PowerManager) getSystemService(Context.POWER_SERVICE);


// 獲取PowerManager.WakeLock物件,後面的引數|表示同時傳入兩個值,最後的是除錯用的Tag
            wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                    | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");


// 點亮螢幕
            wl.acquire();


// 得到鍵盤鎖管理器物件
            km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            kl = km.newKeyguardLock("unLock");
// 解鎖
            kl.disableKeyguard();
            sucCount++;
        } else {
// 鎖屏
            kl.reenableKeyguard();
// 釋放wakeLock,關燈
            wl.release();
// failCount++;
        }


    }


    @Override
    public void onClick(View v) {
// TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.button1:
                String timeString = timeEditText.getText().toString();
                String delayString = delayEditText.getText().toString();


                Log.e(tag, "time-->" + timeString + ",delay--->" + delayString);

                sucCount = 0;
                failCount = 0;

                if (timeString.equals("") || (timeString.length() < 0)) {
                    Toast.makeText(MainActivity.this, "請輸入正確的次數",
                            Toast.LENGTH_SHORT).show();
                    return;
                } else {


                    startBtn.setEnabled(false);
                    stopBtn.setEnabled(true);

                    time = Integer.parseInt(timeString);
                    delay = Integer.parseInt(delayString);
                    Log.e(tag, "time-->" + time + ",delay--->" + delay);
                    timeCount = time;
                    handler.postDelayed(wakelockRunnable, 1000);
                }


                break;


            case R.id.button2:


                handler.removeCallbacks(wakelockRunnable);
                startBtn.setEnabled(true);
                stopBtn.setEnabled(false);
                Log.e(tag, "stopbutton點選停止");
                break;


            default:

                break;
        }


    }


    Runnable wakelockRunnable = new Runnable() {


        @Override
        public void run() {
// TODO Auto-generated method stub
            ScreenLock();

            startBtn.setEnabled(false);
            stopBtn.setEnabled(true);


            timemid = time - 1;
            time = timemid;

            if (time > 0) { // 不是執行一次
                startBtn.setEnabled(false);
                stopBtn.setEnabled(true);
                handler.removeCallbacks(wakelockRunnable);

                Log.e(tag, "time >0 >>>>執行次數:" + timeCount + ";當前執行:" + timemid + "\n成功次數:" + sucCount + ";失敗次數:" + failCount);
                String string = "執行次數:" + timeCount + ";當前執行:" + timemid + "\n成功次數:" + sucCount + ";失敗次數:" + failCount;
                int msgwhat = GUI_DOING;
                sendmsg(msgwhat, string);

                handler.postDelayed(wakelockRunnable, 2000);
            } else {
// 一次執行完成
                startBtn.setEnabled(true);
                stopBtn.setEnabled(false);
//send mesg
                Log.e(tag, "time <0 >>>>執行次數:" + timeCount + ";當前執行:" + timemid + "\n成功次數:" + sucCount + ";失敗次數:" + failCount);

                String string = "執行次數:" + timeCount + ";當前執行:" + timemid + "\n成功次數:" + sucCount + ";失敗次數:" + failCount;
                int msgwhat = GUI_FINISH;

                sendmsg(msgwhat, string);
                handler.removeCallbacks(wakelockRunnable);
            }


        }
    };


    @Override
    protected void onDestroy() {
// TODO Auto-generated method stub
        super.onDestroy();
        handler.removeCallbacks(wakelockRunnable);

        MainActivity.this.finish();
        Log.e(tag, "finish");
    }


    protected void sendmsg(int meswhat, String string) {
// TODO Auto-generated method stub
        Message msg = new Message();
        msg.what = GUI_FINISH;
        msg.obj = string;
        handler.sendMessage(msg);
        Log.e(tag, "send message");
    }


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


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


    private void ScreenLock() {
// TODO Auto-generated method stub
        devAdmReceiver = new ComponentName(MainActivity.this, Darclass.class);
        mDPM = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);


        if (!mDPM.isAdminActive(devAdmReceiver)) {
            Intent intent = new Intent(
                    DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);


            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                    devAdmReceiver);


            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                    "裝置管理涉及的管理許可權,下面是清單,一次性啟用!");
            Log.e(tag, "新增裝置許可權");


            startActivityForResult(intent, REQUEST_ENABLE);


        } else {
            mDPM.lockNow();
            long locknow = System.currentTimeMillis();
            Log.e(tag, "locknow---syscurrenttime>>>" + locknow);

            try {
                Thread.sleep(delay * 1000L);
                Log.e(tag, " 延遲" + delay + "s後亮屏");
            } catch (InterruptedException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }

            Log.e(tag, "wakeandunlock");
            wakeAndUnlock(true);
            Log.e(tag, "wakeandunlock---間隔時間>>>"
                    + (System.currentTimeMillis() - locknow));
        }
    }


}


首先建立一個空的接收者起名為Darlass 
package com.example.unruly_zhao.powermanager_wakelock;

import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;

/**
 * Created by Unruly_Zhao on 2017/9/16.
 */

public class Darclass extends DeviceAdminReceiver {
    @Override
    public DevicePolicyManager getManager(Context context) {
        Log.i("XiaoMaGuo", "呼叫了getManager()方法");
        return super.getManager(context);
    }

    @Override
    public ComponentName getWho(Context context) {
        Log.i("XiaoMaGuo", "呼叫了getWho()方法");
        return super.getWho(context);
    }
}

建立一個廣播接收器LockScreen
package com.example.unruly_zhao.powermanager_wakelock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Created by Unruly_Zhao on 2017/9/16.
 */

public class LockScreen extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}
Layout xml  佈局 activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.unruly_zhao.powermanager_wakelock.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >


        <TextView

            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="       次數:"
            android:textAppearance="?android:attr/textAppearanceMedium" />


        <EditText
            android:id="@+id/_time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" >

            <requestFocus />
        </EditText>

    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >


        <TextView
            android:id="@+id/_jiange"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="       間隔:"
            android:textAppearance="?android:attr/textAppearanceMedium" />


        <EditText
            android:id="@+id/jiangeshuzi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="number" />
    </LinearLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >


        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button1"
            android:layout_below="@+id/button1"
            android:layout_marginTop="30dp"
            android:text="      停止      " />


        <TextView
            android:id="@+id/ttextviewResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="71dp"
            android:textAppearance="?android:attr/textAppearanceMedium" />


        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            />


        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="       開始      "
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>


        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/button2"
            android:layout_marginTop="14dp"
            android:text="使用說明:第一次使用請點選開始,啟用裝置."
            android:textAppearance="?android:attr/textAppearanceMedium" />


    </RelativeLayout>


</LinearLayout>

建立一個xml檔案不會的可以查下資料如何建立

在res/xml下新建一個xml檔案,填入如下程式碼(需要什麼功能填什麼功能,<force-lock/>這個是,不用全寫)想要深入理解的可以都查查其他的

powermanager.xml 

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">

  <uses-policies>
    <force-lock />
  </uses-policies>

</device-admin>

清單檔案所加的許可權和配置

第二個回報紅色 alt+Enter 解決掉它  很多部落格都寫可能需要第二個  我可以明確告訴你第二個不在絕對實現不了 

他們那個可能版低 ,反正我是沒實現

 <uses-permission android:name="android.permission.WAKE_LOCK" />

  <uses-permission android:name="android.permission.DEVICE_POWER" />

最後在清單檔案中不要忘記這兩個接收器實現下

這是我的名字改成自己的  

 <receiver android:name=".LockScreen"></receiver>

        <receiver
            android:name=".Darclass"
            android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/powermanager"/>
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
            </intent-filter>
        </receiver>