类似360 的那个小球,一直悬浮在手机桌面上,点击时跳转其他界面
先说一下这个APK,为什么要说呢,因为安装完看不见图标,然后你会发现什么都没有,先去应用设置里,这个需要显示悬浮框的权限,而且我还设置了开机自启,这个也需要用户开启,默认都是不开起的(反正小米的是这样)
要实现这些,首先需要添加权限,AndroidManifest.xml里
<!--service 需要-->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<!-- 开机自启 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!--扫描本地文件-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
我这里加入了上一个读取本地文件功能
应用不显示图标,形如
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<data android:host="AuthActivity" android:scheme="android.cl.com.suspensionball.floder" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
在activity 里添加date 属性,后面的包名随便写一个,我们只是要不显示图标
然后是开机自启:监听 RECEIVE_BOOT_COMPLETED 广播嘛,AndroidManifest.xml里
<receiver android:name="BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
由于现在android手机系统的缘故,安装在SD卡里的很多应用接收不到广播信息,所以需要修改安装位置,
AndroidManifest.xml里<manifest>里添加android:installLocation="internalOnly"
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
package="android.cl.com.suspensionball" >
然后写一个广播接收者
import android.cl.com.suspensionball.service.TopFloatService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Created by Administrator on 2016/1/21.
*/
public class BootBroadcastReceiver extends BroadcastReceiver {
//重写onReceive方法
@Override
public void onReceive(Context context, Intent intent) {
//后边的XXX.class就是要启动的服务
//开机 BOOT_COMPLETED
Intent service = new Intent(context,TopFloatService.class);
context.startService(service);
Log.v("TAG", "开机自动服务自动启动.....");
}
}
转到要启动的服务就好了
我的service 用的烂的一塌糊涂,主体部分基本上是参考前辈的 http://www.ddvip.com/tech/1000184211_pall.html
看看service
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.cl.com.suspensionball.MyWindowManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
public class TopFloatService extends Service {
/**
* 用于在线程中创建或移除悬浮窗。
*/
private Handler handler = new Handler();
/**
* 定时器,定时进行检测当前应该创建还是移除悬浮窗。
*/
private Timer timer;
/**
* onBind 是 Service 的虚方法,因此我们不得不实现它。
* 返回 null,表示客户端不能建立到此服务的连接。
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 开启定时器,每隔0.5秒刷新一次
if (timer == null) {
timer = new Timer();
timer.scheduleAtFixedRate(new RefreshTask(), 0, 500);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
// Service被终止的同时也停止定时器继续运行
timer.cancel();
timer = null;
}
class RefreshTask extends TimerTask {
@Override
public void run() {
// 当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗。
if (isHome() && !MyWindowManager.isWindowShowing()) {
handler.post(new Runnable() {
@Override
public void run() {
MyWindowManager.createSmallWindow(getApplicationContext());
}
});
}
// 当前界面不是桌面,且有悬浮窗显示,则移除悬浮窗。
else if (!isHome() && MyWindowManager.isWindowShowing()) {
handler.post(new Runnable() {
@Override
public void run() {
MyWindowManager.removeSmallWindow(getApplicationContext());
MyWindowManager.removeBigWindow(getApplicationContext());
}
});
}
// 当前界面是桌面,且有悬浮窗显示,则更新内存数据。
else if (isHome() && MyWindowManager.isWindowShowing()) {
handler.post(new Runnable() {
@Override
public void run() {
MyWindowManager.updateUsedPercent(getApplicationContext());
}
});
}
}
}
/**
* 判断当前界面是否是桌面
*/
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);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo ri : resolveInfo) {
names.add(ri.activityInfo.packageName);
}
return names;
}
}
然后是小悬浮框的view
import java.lang.reflect.Field;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FloatWindowSmallView extends LinearLayout {
/**
* 记录小悬浮窗的宽度
*/
public static int viewWidth;
/**
* 记录小悬浮窗的高度
*/
public static int viewHeight;
/**
* 记录系统状态栏的高度
*/
private static int statusBarHeight;
/**
* 用于更新小悬浮窗的位置
*/
private WindowManager windowManager;
/**
* 小悬浮窗的参数
*/
private WindowManager.LayoutParams mParams;
/**
* 记录当前手指位置在屏幕上的横坐标值
*/
private float xInScreen;
/**
* 记录当前手指位置在屏幕上的纵坐标值
*/
private float yInScreen;
/**
* 记录手指按下时在屏幕上的横坐标的值
*/
private float xDownInScreen;
/**
* 记录手指按下时在屏幕上的纵坐标的值
*/
private float yDownInScreen;
/**
* 记录手指按下时在小悬浮窗的View上的横坐标的值
*/
private float xInView;
/**
* 记录手指按下时在小悬浮窗的View上的纵坐标的值
*/
private float yInView;
public FloatWindowSmallView(Context context) {
super(context);
windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
LayoutInflater.from(context).inflate(R.layout.floatball, this);
View view = findViewById(R.id.small_window_layout);
viewWidth = view.getLayoutParams().width;
viewHeight = view.getLayoutParams().height;
TextView percentView = (TextView) findViewById(R.id.percent);
percentView.setText(MyWindowManager.getUsedPercentValue(context));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
xInView = event.getX();
yInView = event.getY();
xDownInScreen = event.getRawX();
yDownInScreen = event.getRawY() - getStatusBarHeight();
xInScreen = event.getRawX();
yInScreen = event.getRawY() - getStatusBarHeight();
break;
case MotionEvent.ACTION_MOVE:
xInScreen = event.getRawX();
yInScreen = event.getRawY() - getStatusBarHeight();
// 手指移动的时候更新小悬浮窗的位置
updateViewPosition();
break;
case MotionEvent.ACTION_UP:
// 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。
if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
openBigWindow();
}
break;
default:
break;
}
return true;
}
/**
* 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。
*
* @param params
* 小悬浮窗的参数
*/
public void setParams(WindowManager.LayoutParams params) {
mParams = params;
}
/**
* 更新小悬浮窗在屏幕中的位置。
*/
private void updateViewPosition() {
mParams.x = (int) (xInScreen - xInView);
mParams.y = (int) (yInScreen - yInView);
windowManager.updateViewLayout(this, mParams);
}
/**
* 打开大悬浮窗,同时关闭小悬浮窗。
*/
private void openBigWindow() {
MyWindowManager.createBigWindow(getContext());
MyWindowManager.removeSmallWindow(getContext());
}
/**
* 用于获取状态栏的高度。
*
* @return 返回状态栏高度的像素值。
*/
private int getStatusBarHeight() {
if (statusBarHeight == 0) {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object o = c.newInstance();
Field field = c.getField("status_bar_height");
int x = (Integer) field.get(o);
statusBarHeight = getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
}
return statusBarHeight;
}
}
居然是继承extends LinearLayout ,我只能说,乡下来的,没见过,
其他直接参考上面那位前辈的, 只是有一个地方,在悬浮框里开启activity时需要加一句话setFlags
findViewById(R.id.btn_folder).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyWindowManager.removeBigWindow(context);
MyWindowManager.removeSmallWindow(context);
Intent intent = new Intent(getContext(), FloderMainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(intent);
}
});
MyWindowManager:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;
public class MyWindowManager {
/**
* 小悬浮窗View的实例
*/
private static FloatWindowSmallView smallWindow;
/**
* 大悬浮窗View的实例
*/
private static FloatWindowBigView bigWindow;
/**
* 小悬浮窗View的参数
*/
private static LayoutParams smallWindowParams;
/**
* 大悬浮窗View的参数
*/
private static LayoutParams bigWindowParams;
/**
* 用于控制在屏幕上添加或移除悬浮窗
*/
private static WindowManager mWindowManager;
/**
* 用于获取手机可用内存
*/
private static ActivityManager mActivityManager;
/**
* 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。
*
* @param context 必须为应用程序的Context.
*
* WindowManager.LayoutParams这个类用于提供悬浮窗所需的参数,其中有几个经常会用到的变量:
type值用于确定悬浮窗的类型,一般设为2002,表示在所有应用程序之上,但在状态栏之下。
flags值用于确定悬浮窗的行为,比如说不可聚焦,非模态对话框等等,属性非常多,大家可以查看文档。
gravity值用于确定悬浮窗的对齐方式,一般设为左上角对齐,这样当拖动悬浮窗的时候方便计算坐标。
x值用于确定悬浮窗的位置,如果要横向移动悬浮窗,就需要改变这个值。
y值用于确定悬浮窗的位置,如果要纵向移动悬浮窗,就需要改变这个值。
width值用于指定悬浮窗的宽度。
height值用于指定悬浮窗的高度。
*/
public static void createSmallWindow(Context context) {
WindowManager windowManager = getWindowManager(context);
int screenWidth = windowManager.getDefaultDisplay().getWidth();
int screenHeight = windowManager.getDefaultDisplay().getHeight();
if (smallWindow == null) {
smallWindow = new FloatWindowSmallView(context);
if (smallWindowParams == null) {
smallWindowParams = new LayoutParams();
smallWindowParams.type = LayoutParams.TYPE_PHONE;
smallWindowParams.format = PixelFormat.RGBA_8888;
smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
| LayoutParams.FLAG_NOT_FOCUSABLE;
smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
smallWindowParams.width = FloatWindowSmallView.viewWidth;
smallWindowParams.height = FloatWindowSmallView.viewHeight;
smallWindowParams.x = screenWidth;
smallWindowParams.y = screenHeight / 2;
}
smallWindow.setParams(smallWindowParams);
windowManager.addView(smallWindow, smallWindowParams);
}
}
/**
* 将小悬浮窗从屏幕上移除。
*
* @param context
* 必须为应用程序的Context.
*/
public static void removeSmallWindow(Context context) {
if (smallWindow != null) {
WindowManager windowManager = getWindowManager(context);
windowManager.removeView(smallWindow);
smallWindow = null;
}
}
/**
* 创建一个大悬浮窗。位置为屏幕正中间。
*
* @param context
* 必须为应用程序的Context.
*/
public static void createBigWindow(Context context) {
WindowManager windowManager = getWindowManager(context);
int screenWidth = windowManager.getDefaultDisplay().getWidth();
int screenHeight = windowManager.getDefaultDisplay().getHeight();
if (bigWindow == null) {
bigWindow = new FloatWindowBigView(context);
if (bigWindowParams == null) {
bigWindowParams = new LayoutParams();
bigWindowParams.x = screenWidth / 2 - FloatWindowBigView.viewWidth / 2;
bigWindowParams.y = screenHeight / 2 - FloatWindowBigView.viewHeight / 2;
bigWindowParams.type = LayoutParams.TYPE_PHONE;
bigWindowParams.format = PixelFormat.RGBA_8888;
bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
bigWindowParams.width = FloatWindowBigView.viewWidth;
bigWindowParams.height = FloatWindowBigView.viewHeight;
}
windowManager.addView(bigWindow, bigWindowParams);
}
}
/**
* 将大悬浮窗从屏幕上移除。
*
* @param context
* 必须为应用程序的Context.
*/
public static void removeBigWindow(Context context) {
if (bigWindow != null) {
WindowManager windowManager = getWindowManager(context);
windowManager.removeView(bigWindow);
bigWindow = null;
}
}
/**
* 更新小悬浮窗的TextView上的数据,显示内存使用的百分比。
*
* @param context
* 可传入应用程序上下文。
*/
public static void updateUsedPercent(Context context) {
if (smallWindow != null) {
TextView percentView = (TextView) smallWindow.findViewById(R.id.percent);
percentView.setText(getUsedPercentValue(context));
}
}
/**
* 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。
*
* @return 有悬浮窗显示在桌面上返回true,没有的话返回false。
*/
public static boolean isWindowShowing() {
return smallWindow != null || bigWindow != null;
}
/**
* 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
*
* @param context
* 必须为应用程序的Context.
* @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。
*/
private static WindowManager getWindowManager(Context context) {
if (mWindowManager == null) {
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
return mWindowManager;
}
/**
* 如果ActivityManager还未创建,则创建一个新的ActivityManager返回。否则返回当前已创建的ActivityManager。
*
* @param context
* 可传入应用程序上下文。
* @return ActivityManager的实例,用于获取手机可用内存。
*/
private static ActivityManager getActivityManager(Context context) {
if (mActivityManager == null) {
mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
}
return mActivityManager;
}
/**
* 计算已使用内存的百分比,并返回。
*
* @param context
* 可传入应用程序上下文。
* @return 已使用内存的百分比,以字符串形式返回。
*/
public static String getUsedPercentValue(Context context) {
String dir = "/proc/meminfo";
try {
FileReader fr = new FileReader(dir);
BufferedReader br = new BufferedReader(fr, 2048);
String memoryLine = br.readLine();
String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
br.close();
long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
long availableSize = getAvailableMemory(context) / 1024;
int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);
return percent + "%";
} catch (IOException e) {
e.printStackTrace();
}
return "悬浮窗";
}
/**
* 获取当前可用内存,返回数据以字节为单位。
*
* @param context
* 可传入应用程序上下文。
* @return 当前可用内存。
*/
private static long getAvailableMemory(Context context) {
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
getActivityManager(context).getMemoryInfo(mi);
return mi.availMem;
}
}
显示的大的悬浮框
import android.cl.com.suspensionball.floder.FloderMainActivity;
import android.cl.com.suspensionball.service.TopFloatService;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class FloatWindowBigView extends LinearLayout {
/**
* 记录大悬浮窗的宽度
*/
public static int viewWidth;
/**
* 记录大悬浮窗的高度
*/
public static int viewHeight;
public FloatWindowBigView(final Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.floatmenu, this);
View view = findViewById(R.id.big_window_layout);
viewWidth = view.getLayoutParams().width;
viewHeight = view.getLayoutParams().height;
Button close = (Button) findViewById(R.id.close);
Button back = (Button) findViewById(R.id.back);
findViewById(R.id.btn_folder).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyWindowManager.removeBigWindow(context);
MyWindowManager.removeSmallWindow(context);
Intent intent = new Intent(getContext(), FloderMainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(intent);
}
});
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 点击关闭悬浮窗的时候,移除所有悬浮窗,并停止Service
MyWindowManager.removeBigWindow(context);
MyWindowManager.removeSmallWindow(context);
Intent intent = new Intent(getContext(), TopFloatService.class);
context.stopService(intent);
}
});
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 点击返回的时候,移除大悬浮窗,创建小悬浮窗
MyWindowManager.removeBigWindow(context);
MyWindowManager.createSmallWindow(context);
}
});
}
}
写一个MainActivity是因为出安装时方便启动,就三句话,setContentView直接干掉,不需要
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent service = new Intent();
service.setClass(this, TopFloatService.class);
//启动服务
startService(service);
//把自身停掉
finish();
}
}
小悬浮框布局
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/small_window_layout"
android:layout_width="60dip"
android:layout_height="25dip"
android:background="@drawable/bg_small"
>
<TextView
android:id="@+id/percent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:textColor="#ffffff"
/>
</LinearLayout>
大悬浮框布局
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/big_window_layout"
android:layout_width="300dip"
android:layout_height="200dip"
android:background="@drawable/bg_big"
android:orientation="vertical"
>
<Button
android:id="@+id/close"
android:layout_width="100dip"
android:layout_height="40dip"
android:layout_gravity="center_horizontal"
android:text="关闭悬浮窗"
android:layout_alignTop="@+id/back"
android:layout_toStartOf="@+id/back" />
<Button
android:id="@+id/back"
android:layout_width="100dip"
android:layout_height="40dip"
android:layout_gravity="center_horizontal"
android:text="返回"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="42dp"
android:layout_marginBottom="40dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="本地文件"
android:id="@+id/btn_folder"
android:layout_above="@+id/close"
android:layout_centerHorizontal="true"
android:layout_marginBottom="34dp" />
</RelativeLayout>