Android 断开电源10秒后自动关机

/**

  • 电源是否连接

*/

public static boolean isPowerConnect = true;

/**

  • 电源断开的秒数

*/

public static int OffSecond = 0;

接着就是PowerStateChangeReceiver:

package com.android.settings;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Handler;

import android.os外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

资料获取→专栏
.Message;

import android.widget.Toast;

public class PowerStateChangeReceiver extends BroadcastReceiver {

private Context context;

@Override

public void onReceive(Context context, Intent intent) {

this.context = context;

Screenshot.OffSecond = 0;

if (“android.intent.action.ACTION_POWER_CONNECTED”.equals(intent

.getAction())) {

Screenshot.isPowerConnect = true;

//Toast.makeText(context, “CONNECTED”, Toast.LENGTH_SHORT).show();

} else if (“android.intent.action.ACTION_POWER_DISCONNECTED”

.equals(intent.getAction())) {

Screenshot.isPowerConnect = false;

//Toast.makeText(context, “DISCONNECTED”, Toast.LENGTH_SHORT).show();

new Thread(new shutdownThread()).start();

}

}

/**

  • Shutdown

  • @param context

*/

public void shutdown(Context context) {

try {

Intent intent = new Intent(

“android.intent.action.ACTION_REQUEST_SHUTDOWN”);

intent.putExtra(“android.intent.extra.KEY_CONFIRM”, false);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent);

} catch (Exception e) {

}

Toast.makeText(context, context.getResources().getString(R.string.shutdown_now), Toast.LENGTH_SHORT).show();

}

public class shutdownThread implements Runnable {

@Override

public void run() {

synchronized (shutdownHandler) {

while (!Screenshot.isPowerConnect) {

try {

Thread.sleep(1000);

Message message = new Message();

message.what = 1;

shutdownHandler.sendMessage(message);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

final Handler shutdownHandler = new Handler(
) {

public void handleMessage(Message msg) {

switch (msg.what) {

case 1:

if (!Screenshot.isPowerConnect) {

Screenshot.OffSecond++;

} else {

Screenshot.OffSecond = 0;

}

if (Screenshot.OffSecond == 10

&& !Screenshot.isPowerConnect) {

shutdown(context);

}

break;

default:

break;

}

}

};

fSecond++;

} else {

Screenshot.OffSecond = 0;

}

if (Screenshot.OffSecond == 10

&& !Screenshot.isPowerConnect) {

shutdown(context);

}

break;

default:

break;

}

}

};

  • 20
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值