android桌面小火箭升空动画

时间:2022-10-07 03:17:51
 public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** 开启小火箭 */
public void start(View view) {
startService(new Intent(this, RocketService.class));
finish();
}
/** 取消小火箭 */
public void cancel(View view) {
stopService(new Intent(this, RocketService.class));
} }
 import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics; //工具类
public class DenstyUtil { /**
* This method converts dp unit to equivalent pixels, depending on device
* density.
*
* @param dp
* A value in dp (density independent pixels) unit. Which we need
* to convert into pixels
* @param context
* Context to get resources and device specific display metrics
* @return A float value to represent px equivalent to dp depending on
* device density
*/
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
} /**
* This method converts device specific pixels to density independent
* pixels.
*
* @param px
* A value in px (pixels) unit. Which we need to convert into db
* @param context
* Context to get resources and device specific display metrics
* @return A float value to represent dp equivalent to px value
*/
public static float convertPixelsToDp(float px, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
} }
 import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context; // 工具类
public class ServiceUtil { /**
* 判断当前该服务是否在运行
*
* @param context
* @param cls
* @return
*/
public static boolean isServiceRunning(Context context, Class<?> cls) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> runningServices = activityManager
.getRunningServices(1024);
for (RunningServiceInfo service : runningServices) {
if (cls.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
 import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import com.charon.rocketfly.R;
import com.charon.rocketfly.RocketActivity;
import com.charon.rocketfly.util.DenstyUtil; public class RocketService extends Service {
protected static final String TAG = "RocketService";
private WindowManager mWindowManager;
private int mWindowWidth;
private int mWindowHeight;
private static View icon;
private static View rocket_launcher; private static AnimationDrawable mFireAnimationDrawable;
private static AnimationDrawable mLauncherAnimationDrawable; private WindowManager.LayoutParams iconParams;
private WindowManager.LayoutParams launcherParams; private static int mLauncherHeight;
private static int mLauncherWidth; private Vibrator mVibrator; // 震动 private Timer timer; private Handler mHandler = new Handler(); @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
super.onCreate();
//
mWindowManager = (WindowManager) this.getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
// 获取手机屏幕的分辨率和密度 (Pixels:像素)
DisplayMetrics displayMetrics = new DisplayMetrics();
mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
mWindowWidth = displayMetrics.widthPixels;
mWindowHeight = displayMetrics.heightPixels; // 取得震动服务的句柄
mVibrator = (Vibrator) this.getApplicationContext().getSystemService(
Context.VIBRATOR_SERVICE);
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "on start command create icon");
createIcon();
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(new RefreshTask(), 0, 500);
}
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
removeIcon();
removeLauncher();
timer.cancel();
timer = null;
super.onDestroy();
} /**
* 创建桌面悬浮窗,一旦点击就变成小火箭
*/
public void createIcon() {
removeIcon();
iconParams = new LayoutParams();
icon = new ImageView(this.getApplicationContext());
Log.e(TAG, "creat icon is not null");
icon.setBackgroundResource(R.drawable.floating_desktop_tips_rocket_bg); icon.setOnTouchListener(new OnTouchListener() {
float startX = 0;
float startY = 0; @Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 手指一旦点击了后,就要去创建小火箭,和下面的发射台,并且给小火箭播放动画
startX = event.getX();
startY = event.getY(); // 小火箭升空图片
icon.setBackgroundResource(R.drawable.rocket_fire); mFireAnimationDrawable = (AnimationDrawable) icon
.getBackground();
mFireAnimationDrawable.start();
iconParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
iconParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
iconParams.y = iconParams.y - iconParams.height
- icon.getHeight() * 2; mWindowManager.updateViewLayout(icon, iconParams); createLauncher(); break;
case MotionEvent.ACTION_MOVE: Log.d(TAG, "action move change the location");
float newX = event.getRawX();
Log.e(TAG, "iconHeight:" + icon.getHeight() + ":::"
+ iconParams.height);
float newY = event.getRawY() - icon.getHeight()
- iconParams.height;
mWindowManager.updateViewLayout(icon, iconParams); iconParams.x = (int) (newX - startX);
iconParams.y = (int) (newY - startY); // 小火箭去移动位置
isReadyToLaunch(event.getRawX(), event.getRawY()); break; case MotionEvent.ACTION_UP:
// 手指抬起的时候,要么小火箭去发射,要么就是恢复到原来的提示图标那样
Log.d(TAG, "action up");
if (isReadyToLaunch((int) event.getRawX(),
(int) event.getRawY())) {
Intent intent = new Intent(RocketService.this,
RocketActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
removeIcon();
removeLauncher();
} else {
Log.e(TAG, "action up create icon.");
createIcon();
icon.setBackgroundResource(R.drawable.floating_desktop_tips_rocket_bg);
} break;
} return true;
}
}); iconParams.gravity = Gravity.LEFT | Gravity.TOP;
iconParams.x = mWindowWidth;
iconParams.y = mWindowHeight / 2;
iconParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
iconParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
iconParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
iconParams.format = PixelFormat.TRANSLUCENT;
iconParams.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE; mWindowManager.addView(icon, iconParams);
} private void removeIcon() {
if (icon != null && icon.getParent() != null) {
mWindowManager.removeView(icon);
icon = null;
}
removeLauncher();
} /**
* 创建桌面发射台
*/
private void createLauncher() {
removeLauncher(); launcherParams = new LayoutParams();
rocket_launcher = new ImageView(this.getApplicationContext());
changelauncherState(false); launcherParams.height = (int) DenstyUtil.convertDpToPixel(80,
this.getApplicationContext());
launcherParams.width = (int) DenstyUtil.convertDpToPixel(200,
this.getApplicationContext());
mLauncherHeight = launcherParams.height;
mLauncherWidth = launcherParams.width; // 这个x、y是起始添加的位置
launcherParams.x = mWindowWidth / 2 - mLauncherWidth / 2;
launcherParams.y = mWindowHeight - mLauncherHeight;
launcherParams.gravity = Gravity.LEFT | Gravity.TOP; Log.d(TAG, "create launcher. width::" + rocket_launcher.getWidth());
launcherParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
launcherParams.format = PixelFormat.TRANSLUCENT;
launcherParams.type = WindowManager.LayoutParams.TYPE_TOAST; mWindowManager.addView(rocket_launcher, launcherParams);
} private void removeLauncher() {
if (rocket_launcher != null && rocket_launcher.getParent() != null) {
mWindowManager.removeView(rocket_launcher);
}
} /**
* 更改发射台的状态
*
* @param isReadFly
* 是否可以进入发射状态
*/
private void changelauncherState(boolean isReadFly) {
if (rocket_launcher == null) {
return;
} if (isReadFly) {
rocket_launcher.setBackgroundResource(R.drawable.desktop_bg_tips_3);
if (mLauncherAnimationDrawable != null) {
mLauncherAnimationDrawable.stop();
}
} else {
rocket_launcher.setBackgroundResource(R.drawable.status_tip); // 创建发射台
mLauncherAnimationDrawable = (AnimationDrawable) rocket_launcher
.getBackground();
if (!mLauncherAnimationDrawable.isRunning()) {
mLauncherAnimationDrawable.start();
}
}
} /**
* 判断是否可以进行发射
*
* @param x
* 当前火箭的距x轴的距离
* @param y
* 当前火箭的距y轴的距离
* @return true为进入发射状态,反之为false
*/
private boolean isReadyToLaunch(float x, float y) {
if ((x > launcherParams.x && x < launcherParams.x
+ launcherParams.width)
&& (y > launcherParams.y)) {
changelauncherState(true);
Log.d(TAG, "is ready to launch.. true");
mVibrator.vibrate(100);
return true;
}
changelauncherState(false);
return false;
} /**
* 判断当前界面是否是桌面
* getRunningTasks(1):返回的个数。当前 运行的那个task。
* get(0):从task中获取到最顶层的activity,这个activity就是当前显示给用户的那个activity了
*/
private boolean isHome() {
ActivityManager mActivityManager = (ActivityManager) getSystemService(
Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
return getHomes().contains(rti.get(0).topActivity.getPackageName());
} /**
* 获得属于桌面的应用的应用包名称
*
* @return 返回包含所有包名的字符串列表
*/
private List<String> getHomes() {
List<String> names = new ArrayList<String>();
PackageManager packageManager = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
// 通过查询,获得所有ResolveInfo对象
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo ri : resolveInfo) {
names.add(ri.activityInfo.packageName);
}
return names;
} private class RefreshTask extends TimerTask { @Override
public void run() {
// 当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗。
if (isHome()) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (icon == null) {
Log.e(TAG,
"refresh task create icon, and the icon is null");
createIcon();
}
}
}); }
// 当前界面不是桌面,且有悬浮窗显示,则移除悬浮窗。
else if (!isHome()) {
mHandler.post(new Runnable() {
@Override
public void run() {
removeIcon();
}
});
}
} } }
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" > <ImageView
android:id="@+id/iv_rocket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="@drawable/rocket_fire" /> <RelativeLayout
android:id="@+id/rl_cloud"
android:layout_width="wrap_content"
android:layout_height="wrap_content" > <ImageView
android:id="@+id/iv_cloud"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/desktop_smoke_m"
android:visibility="gone" /> <ImageView
android:id="@+id/iv_cloud_line"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/iv_cloud"
android:layout_centerHorizontal="true"
android:background="@drawable/desktop_smoke_t"
android:visibility="gone" />
</RelativeLayout> </RelativeLayout>
 import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout; import com.charon.rocketfly.setvice.RocketService;
import com.charon.rocketfly.util.ServiceUtil; /**
* 小火箭升空界面
* @author dr
*/
public class RocketActivity extends Activity {
protected static final String TAG = "RocketActivity";
private ImageView iv_rocket;
private ImageView iv_cloud;
private ImageView iv_cloud_line;
private RelativeLayout rl_cloud; private AnimationDrawable fireAnimationDrawable; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rocket);
findView();
initView();
} private void findView() {
iv_rocket = (ImageView) findViewById(R.id.iv_rocket);
iv_cloud = (ImageView) findViewById(R.id.iv_cloud);
iv_cloud_line = (ImageView) findViewById(R.id.iv_cloud_line);
rl_cloud = (RelativeLayout) findViewById(R.id.rl_cloud);
} private void initView() {
iv_rocket.setPressed(true);
iv_rocket.setFocusable(true);
iv_rocket.setVisibility(View.VISIBLE);
} @Override
protected void onStart() {
super.onStart();
iv_rocket.setBackgroundResource(R.drawable.rocket_fire);
fireAnimationDrawable = (AnimationDrawable) iv_rocket.getBackground();
fireAnimationDrawable.start(); fly();
} /**
* 火箭飞起来的动画,同时下方播放冒烟的动画
*/
private void fly() {
Log.e(TAG, "fly....");
Animation animation = AnimationUtils.loadAnimation(
this.getApplicationContext(), R.anim.rocket_up);
animation.setFillAfter(true); animation.setAnimationListener(new AnimationListener() { @Override
public void onAnimationStart(Animation animation) {
// 开始发射的时候去博凡动画
MediaPlayer player = MediaPlayer.create(RocketActivity.this,
R.raw.rocket);
player.setLooping(false);
player.setVolume(1.0f, 1.0f);
player.start(); AlphaAnimation cloudAppearAnimation = new AlphaAnimation(0.1f,
1.0f);
cloudAppearAnimation.setDuration(500); Animation appearAnimation = new AlphaAnimation(0.0f, 1.0f);
appearAnimation.setDuration(500);
appearAnimation.setStartOffset(250); iv_cloud.startAnimation(cloudAppearAnimation);
iv_cloud_line.startAnimation(appearAnimation);
} @Override
public void onAnimationRepeat(Animation animation) {
} @Override
public void onAnimationEnd(Animation animation) {
// 火箭播放完成后就去把云彩都消失
removeClound();
if (!ServiceUtil.isServiceRunning(RocketActivity.this,
RocketService.class)) {
startService(new Intent(RocketActivity.this
.getApplicationContext(), RocketService.class));
}
}
}); iv_rocket.startAnimation(animation); createClound();
} private void createClound() {
iv_cloud.setVisibility(View.VISIBLE);
iv_cloud_line.setVisibility(View.VISIBLE);
} private void removeClound() {
AlphaAnimation disappearAnimation = new AlphaAnimation(1.0f, 0.0f);
disappearAnimation.setDuration(1000);
disappearAnimation.setFillAfter(true);
disappearAnimation
.setInterpolator(new AccelerateDecelerateInterpolator()); disappearAnimation.setAnimationListener(new AnimationListener() { @Override
public void onAnimationStart(Animation animation) {
} @Override
public void onAnimationRepeat(Animation animation) {
} @Override
public void onAnimationEnd(Animation animation) {
iv_rocket.setVisibility(View.GONE);
iv_cloud.setVisibility(View.GONE);
iv_cloud_line.setVisibility(View.GONE); finish();
}
});
rl_cloud.startAnimation(disappearAnimation);
}
}
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.charon.rocketfly"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- 震动 -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.charon.rocketfly.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <activity
android:name="com.charon.rocketfly.RocketActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
<service android:name="com.charon.rocketfly.setvice.RocketService" />
</application> </manifest>

DEMO下载地址:http://download.csdn.net/detail/androidsj/7952437