近日,做了一个长按powerkey触发dialog然后包含“关机”,"重启",“飞行模式”三个button功能的应用。现将该应用的主文件做一下记录,方便日后查阅:
软件版本:android4.4
//源码如下:
package com.heimi.power;
import com.heimi.power.R;
import android.app.Activity;
import android.app.Service;
import android.content.pm.ActivityInfo;
import android.os.*;
import android.view.View;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.util.Log;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Context;
import android.content.ComponentName;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.provider.Settings;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.AnimatorSet;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
public class PowerKey extends Activity implements OnClickListener{
private Animation loadingAnim;
private RelativeLayout loading;
private ImageView checkCircle;
private ImageView restartView, poweroffView, airView, bg;
private TextView cancelView, resView, powView, aiView;
private final int CLICK_CANCEL = 1;
private final int CLICK_RESET = 2;
private final int CLICK_POWER = 3;
private final int CLICK_AIR = 4;
private final int SCREEN_OFF = 1;
private final int SLEEP_DUR = 3;
private PowerManager mPM;
private static boolean finish_type = false;
static final String ACTION = "android.intent.action.SCREEN_OFF";
static final String ANAME = "PowerKey";
public static final String BACK_PROP = "sys.factorytest.keytest";
private static boolean recvFlag = false;
protected BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)){
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn.getClassName().contains(ANAME)) {
//context.unregisterReceiver(broadcastReceiver);
//recvFlag = false;
PowerKey.super.finish();
}
}
}
};
private void endAnim(final View img, boolean type) {
ObjectAnimator oba =
ObjectAnimator.ofFloat(img, "translationY", 0, 12f, -300f);
if (type) {
oba = ObjectAnimator.ofFloat(img, "translationY", 0, -12f, 300f);
}
AnimatorSet SetY = new AnimatorSet();
SetY.setDuration(800);
SetY.setTarget(img);
SetY.play(oba);
SetY.start();
}
private void displayAnim(final View img, boolean type) {
ObjectAnimator oba =
ObjectAnimator.ofFloat(img, "translationY", -300f, 15f, -8f, 0);
if (type) {
oba = ObjectAnimator.ofFloat(img, "translationY", 300f, -15f, 8f, 0);
}
AnimatorSet SetY = new AnimatorSet();
SetY.setDuration(500);
SetY.setTarget(img);
SetY.play(oba);
SetY.start();
}
private void startAnimator() {
ValueAnimator alphaAnimator = ValueAnimator.ofFloat(0, 1);
alphaAnimator.setDuration(600);
alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
float currentValue = (Float) animator.getAnimatedValue();
bg.setAlpha(currentValue);
}
});
alphaAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
displayAnim(cancelView, true);
displayAnim(airView, false);
displayAnim(aiView, false);
displayAnim(poweroffView, false);
displayAnim(powView, false);
displayAnim(restartView, false);
displayAnim(resView, false);
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
alphaAnimator.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (getAirplaneModeStatus()) {
finish_type = false;
} else {
finish_type = true;
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
//启动加载动画
private void startLoadingAnimation() {
if (loadingAnim != null && loading != null) {
stopLoadingAnimation();
loading.setVisibility(View.VISIBLE);
checkCircle.setVisibility(View.VISIBLE);
checkCircle.startAnimation(loadingAnim);
}
}
//停止加载动画
private void stopLoadingAnimation() {
if (loadingAnim != null && loading != null) {
loadingAnim.cancel();
loading.setVisibility(View.INVISIBLE);
checkCircle.clearAnimation();
checkCircle.setVisibility(View.GONE);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(broadcastReceiver, filter, null, null);
recvFlag = true;
*/
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.main);
bg = (ImageView) findViewById(R.id.bg);
resView = (TextView) findViewById(R.id.tv_restart);
powView = (TextView) findViewById(R.id.tv_shutdown);
aiView = (TextView) findViewById(R.id.tv_sleep);
cancelView = (TextView) findViewById(R.id.iv_cancel);
cancelView.setOnClickListener(this);
cancelView.setTag(CLICK_CANCEL);
airView = (ImageView) findViewById(R.id.iv_sleep);
airView.setOnClickListener(this);
airView.setTag(CLICK_AIR);
if (getAirplaneModeStatus())
((TextView) findViewById(R.id.tv_sleep)).setText(R.string.sleep_now);
restartView = (ImageView) findViewById(R.id.iv_restart);
restartView.setOnClickListener(this);
restartView.setTag(CLICK_RESET);
poweroffView = (ImageView) findViewById(R.id.iv_shutdown);
poweroffView.setOnClickListener(this);
poweroffView.setTag(CLICK_POWER);
mPM = (PowerManager) PowerKey.this.getSystemService(Context.POWER_SERVICE);
loading = (RelativeLayout) findViewById(R.id.load_pro_rel);
checkCircle = (ImageView) findViewById(R.id.check_circle);
loadingAnim = AnimationUtils.loadAnimation(this, R.anim.sleep_animation);
loadingAnim.setInterpolator(new LinearInterpolator());
startAnimator();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(broadcastReceiver, filter);
/*if (!recvFlag) {
registerReceiver(broadcastReceiver, filter);
recvFlag = true;
}*/
}
@Override
public void onRestart() {
super.onRestart();
}
@Override
protected void onDestroy() {
unregisterReceiver(broadcastReceiver);
/* if (recvFlag) {
unregisterReceiver(broadcastReceiver);
recvFlag = false;
}*/
super.onDestroy();
}
//获取飞行模式关闭或开启状态
private boolean getAirplaneModeStatus() {
boolean status = Settings.Global.getInt(this.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) == 1 ? true : false;
return status;
}
//开启或关闭飞行模式
private void setAirplaneMode(Context context, boolean enable) {
Settings.Global.putInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
Intent airIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
airIntent.putExtra("state", enable);
context.sendBroadcast(airIntent);
}
private void setAllDisable() {
cancelView.setClickable(false);
airView.setClickable(false);
poweroffView.setClickable(false);
restartView.setClickable(false);
}
@Override
public void finish() {
setAllDisable();
if (finish_type) {
ValueAnimator alphaAnimator = ValueAnimator.ofFloat(1, 0);
alphaAnimator.setDuration(800);
alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
float currentValue = (Float) animator.getAnimatedValue();
bg.setAlpha(currentValue);
}
});
alphaAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
endAnim(cancelView, true);
endAnim(airView, false);
endAnim(aiView, false);
endAnim(poweroffView, false);
endAnim(powView, false);
endAnim(restartView, false);
endAnim(resView, false);
}
@Override
public void onAnimationEnd(Animator animation) {
/* if (recvFlag) {
unregisterReceiver(broadcastReceiver);
recvFlag = false;
}*/
if (getAirplaneModeStatus()) {
//turn off the screen if we are at air-plane mode
mPM.goToSleep(SystemClock.uptimeMillis());
}
System.exit(0);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
alphaAnimator.start();
} else {
SystemProperties.set(BACK_PROP, "1");
ObjectAnimator oba = ObjectAnimator.ofFloat(cancelView, "translationY", 0, -12f, 300f);
oba.setDuration(800);
oba.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
endAnim(airView, false);
endAnim(aiView, false);
endAnim(poweroffView, false);
endAnim(powView, false);
endAnim(restartView, false);
endAnim(resView, false);
}
@Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
super.onAnimationEnd(animation);
startLoadingAnimation();
Message msg = mHandler.obtainMessage();
msg.what = SCREEN_OFF;
mHandler.sendMessageDelayed(msg, SLEEP_DUR * 1000);
}
});
oba.start();
}
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SCREEN_OFF:
stopLoadingAnimation();
/*if (recvFlag) {
unregisterReceiver(broadcastReceiver);
recvFlag = false;
}*/
mPM.goToSleep(SystemClock.uptimeMillis());
SystemProperties.set(BACK_PROP, "0");
PowerKey.super.finish();
break;
}
}
};
public void onClick(View v) {
SystemProperties.set("service.bootanim.exit","0");
int tag = (Integer) v.getTag();
switch (tag) {
case CLICK_CANCEL:
if (getAirplaneModeStatus()) {
finish_type = false;
} else {
finish_type = true;
}
finish();
break;
case CLICK_AIR:
finish_type = false;
/*if (getAirplaneModeStatus()) {
setAirplaneMode(this, false);
airView.setImageDrawable(getResources().getDrawable(R.drawable.dormancy_pattern_pressed));
} else {
setAirplaneMode(this, true);
airView.setImageDrawable(getResources().getDrawable(R.drawable.dormancy_pattern_normal));
}*/
if (!getAirplaneModeStatus()) {
setAirplaneMode(this, true);
finish();
}
break;
case CLICK_RESET:
Intent resetIntent = new Intent(Intent.ACTION_REBOOT);
resetIntent.putExtra("nowait", 1);
resetIntent.putExtra("interval", 1);
resetIntent.putExtra("window", 0);
mPM.setLightFlash(255, 2, 0, 0, mPM.PRIORITY_POWER_DOWN_LED);
sendBroadcastAsUser(resetIntent, UserHandle.ALL);
break;
case CLICK_POWER:
Intent powerIntent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
powerIntent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
//其中false换成true,会弹出是否关机的确认窗口
powerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mPM.setLightFlash(255, 2, 0, 0, mPM.PRIORITY_POWER_DOWN_LED);
startActivity(powerIntent);
break;
}
}
}
AndroidManifest.xml代码片:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.heimi.power"
android:sharedUserId="android.uid.system"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.SHUTDOWN"></uses-permission>
<!--uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission-->
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" >
<activity
android:name="com.heimi.power.PowerKey"
android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SCREEN_OFF" />
<!--category android:name="android.intent.category.LAUNCHER" -->
</intent-filter>
</activity>
</application>
</manifest>
布局文件main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/bg"
android:scaleType="fitXY"
android:src="@drawable/background"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<View
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="70px"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv_sleep"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_marginTop="70px"
android:contentDescription="@null"
android:src="@drawable/sleep_selector" />
<TextView
android:id="@+id/tv_sleep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10px"
android:layout_marginBottom="15px"
android:text="@string/sleep"
android:textColor="@color/blue"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="70px"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv_restart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_marginTop="70px"
android:contentDescription="@null"
android:src="@drawable/restart_selector" />
<TextView
android:id="@+id/tv_restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10px"
android:layout_marginBottom="15px"
android:text="@string/restart"
android:textColor="@color/blue"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight = "1"/>
<LinearLayout
android:layout_width="70px"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv_shutdown"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_marginTop="70px"
android:contentDescription="@null"
android:src="@drawable/shutdown_selector" />
<TextView
android:id="@+id/tv_shutdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10px"
android:layout_marginBottom="15px"
android:text="@string/shutdown"
android:textColor="@color/blue"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight = "1"/>
</LinearLayout>
<TextView
android:id="@+id/iv_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10px"
android:clickable="true"
android:padding="10px"
android:text="@string/cancel"
android:textColor="@color/white"
android:drawablePadding="10px"
android:gravity="center"
android:drawableTop="@drawable/cancle_selector" />
<include layout="@layout/loading_layout"
android:id="@+id/load_pro_rel"/>
</RelativeLayout>
进入休眠模式的旋转动画布局loading_layout.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:background="#00000000" >
<ImageView
android:id="@+id/loading_center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@null"
android:src="@drawable/center" />
<ImageView
android:id="@+id/check_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@null"
android:src="@drawable/loading_circle" />
<TextView
style="@style/text_common_white"
android:layout_below="@+id/check_circle"
android:layout_centerHorizontal="true"
android:text="@string/go_sleep" />
</RelativeLayout>
O(∩_∩)O~,。。。。先告一段落,未完待续!