待机唤醒(亮屏灭屏)

来源:互联网 发布:mac 查看文件的路径 编辑:程序博客网 时间:2024/05/01 10:29


最近研究了很久 ,待机唤醒不知道从何下手,开始使用powermanager,可是发现根本就不起作用.


MainActivity  

package com.example.wakeup;


import junit.runner.Version;
import android.R.integer;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.admin.DevicePolicyManager;
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.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.support.annotation.StringDef;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
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);


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


}


/**
* 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));
}
}


}


关闭屏幕 ,熄灭屏幕 用广播的形式传出去

/**
 * 
 */
package com.example.wakeup;


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


/**
 * @author hejunwang
 *
 */
public class LockScreen extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub


}


}



package com.example.wakeup;


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


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); 
   } 
    


}



layout 布局文件


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".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:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="       开始      " />


        <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>



0 0