/**
- 电源是否连接
*/
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;
}
}
};