├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable
│ │ │ │ └── eye_open.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ ├── xml
│ │ │ │ ├── assist_service.xml
│ │ │ │ └── accessibility.xml
│ │ │ └── layout
│ │ │ │ ├── view_float.xml
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── pl
│ │ │ │ └── recent
│ │ │ │ ├── service
│ │ │ │ ├── voiceInteraction
│ │ │ │ │ ├── BBVoiceInteractionService.java
│ │ │ │ │ ├── BBVoiceInteractionSessionService.java
│ │ │ │ │ └── BBVoiceInteractionSession.java
│ │ │ │ └── AccessibilityMonitorService.java
│ │ │ │ ├── MyApplication.java
│ │ │ │ ├── utils
│ │ │ │ ├── LogUtil.java
│ │ │ │ └── RunningTaskUtil.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ └── views
│ │ │ │ └── TipViewController.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── pl
│ │ │ └── recent
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── pl
│ │ └── recent
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── pics
├── Improved.gif
└── Original.gif
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── COPYING.WTFPL
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/pics/Improved.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/penglu20/RecentTask/HEAD/pics/Improved.gif
--------------------------------------------------------------------------------
/pics/Original.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/penglu20/RecentTask/HEAD/pics/Original.gif
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/penglu20/RecentTask/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/eye_open.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/penglu20/RecentTask/HEAD/app/src/main/res/drawable/eye_open.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | .idea
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | RecentTask
3 | 打开右上角开关,在弹出的对话框中点击 `确认`。\n\n开启后,即可在微信,QQ等应用聊天页面中点击或长按文字聊天气泡,然后就会打开 BigBang 页面。\n\n 此功能完全不需要root您的手机。只需您打开服务,弹窗提示您的授权时,点击确认便可。
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/assist_service.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/service/voiceInteraction/BBVoiceInteractionService.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.service.voiceInteraction;
2 |
3 | import android.annotation.TargetApi;
4 | import android.os.Build;
5 | import android.service.voice.VoiceInteractionService;
6 |
7 | /**
8 | * Created by penglu on 2016/12/16.
9 | */
10 |
11 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
12 | public class BBVoiceInteractionService extends VoiceInteractionService {
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/test/java/com/pl/recent/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/COPYING.WTFPL:
--------------------------------------------------------------------------------
1 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2 | Version 2, December 2004
3 |
4 | Copyright (C) 2004 Sam Hocevar
5 |
6 | Everyone is permitted to copy and distribute verbatim or modified
7 | copies of this license document, and changing it is allowed as long
8 | as the name is changed.
9 |
10 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
12 |
13 | 0. You just DO WHAT THE FUCK YOU WANT TO.
14 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/MyApplication.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 |
7 | /**
8 | * Created by l4656_000 on 2015/11/14.
9 | */
10 | public class MyApplication extends Application {
11 | private static Context instance;
12 | @Override
13 | public void onCreate() {
14 | super.onCreate();
15 | instance=this;
16 |
17 | }
18 |
19 | public static Context getInstance(){
20 | return instance;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in E:\Android\android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/service/voiceInteraction/BBVoiceInteractionSessionService.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.service.voiceInteraction;
2 |
3 | import android.annotation.TargetApi;
4 | import android.os.Build;
5 | import android.os.Bundle;
6 | import android.service.voice.VoiceInteractionSession;
7 | import android.service.voice.VoiceInteractionSessionService;
8 |
9 | /**
10 | * Created by penglu on 2016/12/16.
11 | */
12 |
13 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
14 | public class BBVoiceInteractionSessionService extends VoiceInteractionSessionService {
15 | @Override
16 | public VoiceInteractionSession onNewSession(Bundle args) {
17 | return new BBVoiceInteractionSession(this);
18 | }
19 |
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1024m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/view_float.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
11 |
12 |
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/pl/recent/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.pl.recent", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/accessibility.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 24
5 | buildToolsVersion "24.0.3"
6 | defaultConfig {
7 | applicationId "com.pl.recent"
8 | minSdkVersion 14
9 | targetSdkVersion 24
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:24.2.1'
28 | testCompile 'junit:junit:4.12'
29 | }
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ##简介
2 | 我目前已知,并且尝试过的获取当前前台应用的方法有如下几种:
3 |
4 | 1. Android5.0以前,使用ActivityManager的getRunningTasks()方法,可以得到应用包名和Activity;
5 | 2. Android5.0以后,通过使用量统计功能来实现,只能得到应用包名;
6 | 3. 通过辅助服务来实现,可以得到包名和Activity;
7 | 4. Android5.0以后,可以通过设备辅助应用程序来实现,能得到包名和Activity,不过这种方式必须用户主动触发(长按Home键)
8 |
9 | **本demo中对这四种方法进行了演示。**
10 |
11 | 目前最常使用的是**第二种**方法,但**要注意的是,只是这样并不够**因为在一些手机上,
12 | 应用发起通知栏消息的时候,或者是下拉通知栏,也会被记录到使用量中,
13 | 就会导致按最近时间排序出现混乱,而且收起通知栏以后,这种混乱并不会被修正,而是必须重新开启一个应用才行。
14 | 比如下图:
15 |
16 | ######未改进版,会将通知栏误判成前台应用中:
17 | 
18 |
19 | ######改进版,正确的判断前台应用:
20 |
21 | 
22 |
23 |
24 |
25 | ##相关文章
26 |
27 | [4种获取前台应用的方法(肯定有你不知道的)](http://www.jianshu.com/p/a513accd40cd)
28 |
29 |
30 | ##License
31 |
32 |
33 | 
34 |
35 |
36 | ```
37 | Copyright © 2016 l465659833
38 | This work is free. You can redistribute it and/or modify it under the
39 | terms of the Do What The Fuck You Want To Public License, Version 2,
40 | as published by Sam Hocevar. See the COPYING file for more details.
41 |
42 | ```
43 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
27 |
28 |
29 |
30 |
31 |
34 |
35 |
36 |
40 |
43 |
44 |
45 |
46 |
47 |
48 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/utils/LogUtil.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.utils;
2 |
3 | import android.content.Context;
4 | import android.content.pm.ApplicationInfo;
5 | import android.util.Log;
6 |
7 | import com.pl.recent.MyApplication;
8 |
9 | /**
10 | * Created by l4656_000 on 2015/11/28.
11 | */
12 | public class LogUtil {
13 |
14 | public static boolean isEshow=true;
15 | public static boolean isWshow=true;
16 | public static boolean isIshow=true;
17 | public static boolean isDshow=true;
18 | public static boolean isVshow=true;
19 | private static boolean isDebug=false;
20 |
21 |
22 | static{
23 | if (isApkDebugable(MyApplication.getInstance())){
24 | isDebug=true;
25 | isEshow=true;
26 | isWshow=true;
27 | isIshow=true;
28 | isDshow=true;
29 | isVshow=true;
30 | }else {
31 | isDebug=false;
32 | isEshow=true;
33 | isWshow=false;
34 | isIshow=false;
35 | isDshow=false;
36 | isVshow=false;
37 | }
38 | }
39 |
40 | public static boolean isApkDebugable(Context context) {
41 | try {
42 | ApplicationInfo info= context.getApplicationInfo();
43 | return (info.flags&ApplicationInfo.FLAG_DEBUGGABLE)== ApplicationInfo.FLAG_DEBUGGABLE;
44 | } catch (Exception e) {
45 |
46 | }
47 | return false;
48 | }
49 |
50 | public static boolean isDebug() {
51 | return isDebug;
52 | }
53 |
54 | public static void setIsDebug(boolean isDebug) {
55 | LogUtil.isDebug = isDebug;
56 | }
57 |
58 | public static void d(String msg){
59 | if(isDshow)
60 | Log.d("RecentTask", msg);
61 | }
62 | public static void d(String tag,String msg){
63 | d(tag+","+msg);
64 | }
65 | public static void e(String msg){
66 | if(isEshow)Log.e("RecentTask", msg);
67 | }
68 | public static void e(String tag,String msg){
69 | e(tag+","+msg);
70 | }
71 | public static void i(String msg){
72 | if(isIshow)Log.i("RecentTask", msg);
73 | }
74 | public static void i(String tag,String msg){
75 | i(tag+","+msg);
76 | }
77 | public static void w(String msg){
78 | if(isWshow)Log.w("RecentTask", msg);
79 | }
80 | public static void w(String tag,String msg){
81 | w(tag+","+msg);
82 | }
83 | public static void v(String msg){
84 | if(isVshow)Log.v("RecentTask", msg);
85 | }
86 | public static void v(String tag,String msg){
87 | v(tag+","+msg);
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/service/voiceInteraction/BBVoiceInteractionSession.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.service.voiceInteraction;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.assist.AssistContent;
5 | import android.app.assist.AssistStructure;
6 | import android.content.ComponentName;
7 | import android.content.Context;
8 | import android.graphics.Bitmap;
9 | import android.os.Build;
10 | import android.os.Bundle;
11 | import android.os.Handler;
12 | import android.service.voice.VoiceInteractionSession;
13 | import android.view.KeyEvent;
14 |
15 | import com.pl.recent.views.TipViewController;
16 |
17 | import static com.pl.recent.MainActivity.HIDE_FLOAT_VIEW_PACKAGE_NAME;
18 |
19 | /**
20 | * Created by penglu on 2016/12/16.
21 | */
22 |
23 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
24 | public class BBVoiceInteractionSession extends VoiceInteractionSession {
25 | private Context mContext;
26 | TipViewController tipViewController;
27 | public BBVoiceInteractionSession(Context context) {
28 | super(context);
29 | mContext=context;
30 | tipViewController=TipViewController.getInstance();
31 | }
32 |
33 | public BBVoiceInteractionSession(Context context, Handler handler) {
34 | super(context, handler);
35 | mContext=context;
36 | }
37 |
38 | @TargetApi(Build.VERSION_CODES.M)
39 | @Override
40 | public void onHandleAssist(Bundle data, AssistStructure structure, AssistContent content) {
41 | super.onHandleAssist(data, structure, content);
42 | ComponentName componentName=structure.getActivityComponent();
43 | if (componentName.getPackageName().equals(HIDE_FLOAT_VIEW_PACKAGE_NAME)){
44 | tipViewController.hide();
45 | }else {
46 | tipViewController.show(1,"");
47 | }
48 |
49 | }
50 |
51 | @Override
52 | public void onHandleAssistSecondary(Bundle data, AssistStructure structure, AssistContent content, int index, int count) {
53 | super.onHandleAssistSecondary(data, structure, content, index, count);
54 | }
55 |
56 | @Override
57 | public void onShow(Bundle args, int showFlags) {
58 | super.onShow(args, showFlags);
59 | new Handler().post(new Runnable() {
60 | @Override
61 | public void run() {
62 | finish();
63 | }
64 | });
65 | }
66 |
67 |
68 | @Override
69 | public void onHide() {
70 | super.onHide();
71 | }
72 |
73 | @Override
74 | public boolean onKeyDown(int keyCode, KeyEvent event) {
75 | return super.onKeyDown(keyCode, event);
76 | }
77 |
78 | @Override
79 | public void onHandleScreenshot(Bitmap screenshot) {
80 | super.onHandleScreenshot(screenshot);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/service/AccessibilityMonitorService.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.service;
2 |
3 | import android.accessibilityservice.AccessibilityService;
4 | import android.accessibilityservice.AccessibilityServiceInfo;
5 | import android.content.Intent;
6 | import android.os.Build;
7 | import android.view.accessibility.AccessibilityEvent;
8 |
9 | import com.pl.recent.views.TipViewController;
10 |
11 | import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_GENERIC;
12 | import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED;
13 | import static android.view.accessibility.AccessibilityEvent.TYPE_VIEW_LONG_CLICKED;
14 | import static com.pl.recent.MainActivity.HIDE_FLOAT_VIEW_PACKAGE_NAME;
15 |
16 |
17 | public class AccessibilityMonitorService extends AccessibilityService {
18 |
19 | private static final String TAG="BigBangMonitorService";
20 |
21 | private CharSequence mWindowClassName;
22 |
23 | private String mCurrentPackage;
24 | TipViewController tipViewController;
25 |
26 | AccessibilityServiceInfo mAccessibilityServiceInfo;
27 |
28 | @Override
29 | public void onCreate() {
30 | super.onCreate();
31 | tipViewController=TipViewController.getInstance();
32 | mAccessibilityServiceInfo=new AccessibilityServiceInfo();
33 | mAccessibilityServiceInfo.feedbackType=FEEDBACK_GENERIC;
34 | mAccessibilityServiceInfo.eventTypes=AccessibilityEvent.TYPE_VIEW_CLICKED|AccessibilityEvent.TYPE_VIEW_LONG_CLICKED|AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
35 | int flag=0;
36 | if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
37 | flag=flag|AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;
38 | }
39 | if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR2){
40 | flag=flag|AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS;
41 | }
42 | mAccessibilityServiceInfo.flags=flag;
43 | mAccessibilityServiceInfo.notificationTimeout=100;
44 | setServiceInfo(mAccessibilityServiceInfo);
45 | }
46 |
47 | @Override
48 | protected void onServiceConnected() {
49 | super.onServiceConnected();
50 | setServiceInfo(mAccessibilityServiceInfo);
51 | }
52 |
53 | @Override
54 | public int onStartCommand(Intent intent, int flags, int startId) {
55 | setServiceInfo(mAccessibilityServiceInfo);
56 | return super.onStartCommand(intent, flags, startId);
57 | }
58 |
59 | @Override
60 | public void onAccessibilityEvent(AccessibilityEvent event) {
61 | int type=event.getEventType();
62 | switch (type){
63 | case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
64 | mWindowClassName = event.getClassName();
65 | mCurrentPackage = event.getPackageName()==null?"":event.getPackageName().toString();
66 | if (mCurrentPackage.equals(HIDE_FLOAT_VIEW_PACKAGE_NAME)){
67 | tipViewController.hide();
68 | }else {
69 | tipViewController.show(1,"");
70 | }
71 | break;
72 | case TYPE_VIEW_CLICKED:
73 | case TYPE_VIEW_LONG_CLICKED:
74 | break;
75 | }
76 | }
77 |
78 | @Override
79 | public void onInterrupt() {
80 |
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent;
2 |
3 | import android.content.ComponentName;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.provider.Settings;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.view.View;
9 | import android.widget.Toast;
10 |
11 | import com.pl.recent.service.AccessibilityMonitorService;
12 | import com.pl.recent.utils.RunningTaskUtil;
13 | import com.pl.recent.views.TipViewController;
14 |
15 | import java.util.Timer;
16 | import java.util.TimerTask;
17 |
18 | public class MainActivity extends AppCompatActivity {
19 | RunningTaskUtil runningTaskUtil;
20 | Timer timer;
21 | TimerTask timerTask;
22 | TipViewController tipViewController;
23 | public static final String HIDE_FLOAT_VIEW_PACKAGE_NAME="com.android.chrome";
24 |
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 | setContentView(R.layout.activity_main);
29 | runningTaskUtil=new RunningTaskUtil(getApplicationContext());
30 | tipViewController=TipViewController.getInstance();
31 |
32 | timer=new Timer();
33 | }
34 |
35 | public void openUsageSettings(View view){
36 | try {
37 | Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
38 | startActivity(intent);
39 | }catch (Throwable e){
40 | Toast.makeText(this,"无法打开系统设置,请手动设置",Toast.LENGTH_SHORT).show();
41 | }
42 | }
43 |
44 | public void setAccissibilityAPP(View view){
45 | try {
46 | Intent intent = new Intent(Settings.ACTION_VOICE_INPUT_SETTINGS);
47 | startActivity(intent);
48 | }catch (Throwable e){
49 | Toast.makeText(this,"无法打开系统设置,请手动设置",Toast.LENGTH_SHORT).show();
50 | }
51 | }
52 |
53 | public void setAccissibilityService(View view){
54 | try {
55 | Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
56 | startActivity(intent);
57 | }catch (Throwable e){
58 | Toast.makeText(this,"无法打开系统设置,请手动设置",Toast.LENGTH_SHORT).show();
59 | }
60 | }
61 |
62 | public void startCheckGetRunningTasks(View view){
63 | if (timerTask!=null) {
64 | timerTask.cancel();
65 | }
66 | timerTask=new TimerTask() {
67 | @Override
68 | public void run() {
69 | ComponentName componentName = runningTaskUtil.getTopActivtyFromLolipopOnwards();
70 | if (componentName.getPackageName().equals(HIDE_FLOAT_VIEW_PACKAGE_NAME)){
71 | tipViewController.hide();
72 | }else {
73 | tipViewController.show(1,"");
74 | }
75 | }
76 | };
77 | timer.schedule(timerTask,1000,1000);
78 | }
79 |
80 | public void startCheckOriginal(View view){
81 | if (timerTask!=null) {
82 | timerTask.cancel();
83 | }
84 | timerTask=new TimerTask() {
85 | @Override
86 | public void run() {
87 | ComponentName componentName = runningTaskUtil.getTopRunningTasksOrigin();
88 | if (componentName.getPackageName().equals(HIDE_FLOAT_VIEW_PACKAGE_NAME)){
89 | tipViewController.hide();
90 | }else {
91 | tipViewController.show(1,"");
92 | }
93 | }
94 | };
95 | timer.schedule(timerTask,1000,1000);
96 | }
97 |
98 | public void startCheckImproved(View view){
99 | if (timerTask!=null) {
100 | timerTask.cancel();
101 | }
102 | timerTask=new TimerTask() {
103 | @Override
104 | public void run() {
105 | ComponentName componentName = runningTaskUtil.getTopRunningTasks();
106 | if (componentName.getPackageName().equals(HIDE_FLOAT_VIEW_PACKAGE_NAME)){
107 | tipViewController.hide();
108 | }else {
109 | tipViewController.show(1,"");
110 | }
111 | }
112 | };
113 | timer.schedule(timerTask,1000,1000);
114 | }
115 |
116 | public void startCheckAccissibility(View view){
117 | Intent intent=new Intent(this, AccessibilityMonitorService.class);
118 | startService(intent);
119 | }
120 |
121 | @Override
122 | protected void onDestroy() {
123 | if (timerTask!=null) {
124 | timerTask.cancel();
125 | }
126 | tipViewController.remove();
127 | super.onDestroy();
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
17 |
18 |
24 |
25 |
31 |
32 |
33 |
37 |
38 |
44 |
45 |
51 |
52 |
58 |
59 |
65 |
66 |
67 |
71 |
72 |
73 |
79 |
80 |
87 |
88 |
94 |
95 |
96 |
102 |
103 |
104 |
108 |
109 |
110 |
116 |
117 |
124 |
125 |
126 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/utils/RunningTaskUtil.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.utils;
2 |
3 | import android.app.ActivityManager;
4 | import android.app.usage.UsageStats;
5 | import android.app.usage.UsageStatsManager;
6 | import android.content.ComponentName;
7 | import android.content.Context;
8 | import android.os.Build;
9 |
10 | import com.pl.recent.MyApplication;
11 |
12 | import java.lang.reflect.Field;
13 | import java.util.Iterator;
14 | import java.util.List;
15 | import java.util.NavigableSet;
16 | import java.util.TreeMap;
17 |
18 | /**
19 | * Created by penglu on 2016/8/14.
20 | */
21 | public class RunningTaskUtil {
22 | private static final String TAG="RunningTaskUtil";
23 | public static final int TWENTYSECOND = 1000 * 20;
24 | public static final int THIRTYSECOND = 1000 * 60 * 60 * 3;
25 | private ActivityManager activityManager;
26 | private UsageStatsManager mUsageStatsManager;
27 | private Field mLastEventField;
28 |
29 | public RunningTaskUtil(Context context){
30 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
31 | mUsageStatsManager = (UsageStatsManager)context.getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
32 | }
33 | activityManager = (ActivityManager)context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
34 | }
35 |
36 | public ComponentName getTopRunningTasks(){
37 | //用两次取当前应用的办法来提高正确性
38 | return getTopRunningTasks(true);
39 | }
40 |
41 | public ComponentName getTopRunningTasks(boolean isFirst){
42 | ComponentName runningTopActivity=null;
43 | String topPackageName =null;
44 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
45 | long time = System.currentTimeMillis();
46 | // We get usage stats for the last 10 seconds
47 | List stats ;
48 | // long start=System.currentTimeMillis();
49 | if (isFirst){
50 | stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - TWENTYSECOND, time);
51 | }else {
52 | stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - THIRTYSECOND, time);
53 | }
54 | // LogUtil.e(TAG,"isFirst="+isFirst+",queryUsageStats cost:"+ (System.currentTimeMillis()-start));
55 | // Sort the stats by the last time used
56 | if(stats != null) {
57 | TreeMap mySortedMap = new TreeMap();
58 | // start=System.currentTimeMillis();
59 | for (UsageStats usageStats : stats) {
60 | mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
61 | }
62 | // LogUtil.e(TAG,"isFirst="+isFirst+",mySortedMap cost:"+ (System.currentTimeMillis()-start));
63 | if(mySortedMap != null && !mySortedMap.isEmpty()) {
64 | NavigableSet keySet=mySortedMap.navigableKeySet();
65 | Iterator iterator=keySet.descendingIterator();
66 | while(iterator.hasNext()){
67 | UsageStats usageStats = mySortedMap.get(iterator.next());
68 | if (mLastEventField==null) {
69 | try {
70 | mLastEventField = UsageStats.class.getField("mLastEvent");
71 | } catch (NoSuchFieldException e) {
72 | break;
73 | }
74 | }
75 | if (mLastEventField!=null) {
76 | int lastEvent = 0;
77 | try {
78 | lastEvent = mLastEventField.getInt(usageStats);
79 | } catch (IllegalAccessException e) {
80 | break;
81 | }
82 | if (lastEvent==1){
83 | topPackageName=usageStats.getPackageName();
84 | break;
85 | }
86 | }else {
87 | break;
88 | }
89 | }
90 | if (topPackageName==null){
91 | topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
92 | if ("com.android.systemui".equals(topPackageName)){
93 | Long currentKey = null;
94 | String tempPackage = topPackageName;
95 | currentKey = (Long) ((TreeMap) mySortedMap).floorKey(mySortedMap.lastKey()-1);
96 | if (currentKey!=null) {
97 | tempPackage = mySortedMap.get(currentKey).getPackageName();
98 | }
99 | if (tempPackage!=null){
100 | if (MyApplication.getInstance().getPackageName().equals(tempPackage)){
101 | currentKey = (Long) ((TreeMap) mySortedMap).floorKey(currentKey-1);
102 | if (currentKey!=null) {
103 | tempPackage = mySortedMap.get(currentKey).getPackageName();
104 | }
105 | }
106 | }
107 | if (tempPackage!=null){
108 | topPackageName=tempPackage;
109 | }
110 | }
111 | }
112 | runningTopActivity=new ComponentName(topPackageName,"");
113 | if (LogUtil.isDebug())LogUtil.d(TAG,topPackageName);
114 | }else {
115 | if (LogUtil.isDebug())LogUtil.d(TAG,"mySortedMap.isEmpty");
116 | if (isFirst){
117 | runningTopActivity = getTopRunningTasks(false);
118 | }else {
119 | runningTopActivity=getTopActivtyFromLolipopOnwards();
120 | }
121 | }
122 | }
123 | if (runningTopActivity.getPackageName().equals(MyApplication.getInstance().getPackageName())){
124 | runningTopActivity = getTopActivtyFromLolipopOnwards();
125 | }
126 | }else {
127 | runningTopActivity = getTopActivtyFromLolipopOnwards();
128 | }
129 | return runningTopActivity;
130 | }
131 |
132 | public ComponentName getTopActivtyFromLolipopOnwards(){
133 | ComponentName runningTopActivity = activityManager.getRunningTasks(1).get(0).topActivity;
134 | if (LogUtil.isDebug())LogUtil.d(TAG,"runningTopActivity="+runningTopActivity.getClassName());
135 | return runningTopActivity;
136 | }
137 |
138 | public ComponentName getTopRunningTasksOrigin(){
139 | ComponentName runningTopActivity=null;
140 | String topPackageName =null;
141 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
142 | long time = System.currentTimeMillis();
143 | // We get usage stats for the last 10 seconds
144 | List stats ;
145 | // long start=System.currentTimeMillis();
146 | stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - TWENTYSECOND, time);
147 | // LogUtil.e(TAG,"isFirst="+isFirst+",queryUsageStats cost:"+ (System.currentTimeMillis()-start));
148 | // Sort the stats by the last time used
149 | if(stats != null) {
150 | TreeMap mySortedMap = new TreeMap();
151 | // start=System.currentTimeMillis();
152 | for (UsageStats usageStats : stats) {
153 | mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
154 | }
155 | // LogUtil.e(TAG,"isFirst="+isFirst+",mySortedMap cost:"+ (System.currentTimeMillis()-start));
156 | if(mySortedMap != null && !mySortedMap.isEmpty()) {
157 | topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
158 | runningTopActivity=new ComponentName(topPackageName,"");
159 | if (LogUtil.isDebug())LogUtil.d(TAG,topPackageName);
160 | }else {
161 | if (LogUtil.isDebug())LogUtil.d(TAG,"mySortedMap.isEmpty");
162 | runningTopActivity=getTopActivtyFromLolipopOnwards();
163 | }
164 | }
165 | if (runningTopActivity.getPackageName().equals(MyApplication.getInstance().getPackageName())){
166 | runningTopActivity = getTopActivtyFromLolipopOnwards();
167 | }
168 | }else {
169 | runningTopActivity = getTopActivtyFromLolipopOnwards();
170 | }
171 | return runningTopActivity;
172 | }
173 |
174 | public boolean needToSet(){
175 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
176 | long time = System.currentTimeMillis();
177 | // We get usage stats for the last 10 seconds
178 | List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*60, time);
179 | if (stats.size()==0){
180 | return true;
181 | }else {
182 | return false;
183 | }
184 | }else {
185 | return false;
186 | }
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/app/src/main/java/com/pl/recent/views/TipViewController.java:
--------------------------------------------------------------------------------
1 | package com.pl.recent.views;
2 |
3 | import android.content.Context;
4 | import android.graphics.PixelFormat;
5 | import android.graphics.Point;
6 | import android.os.Build;
7 | import android.os.Handler;
8 | import android.os.Looper;
9 | import android.os.Message;
10 | import android.util.DisplayMetrics;
11 | import android.view.Gravity;
12 | import android.view.MotionEvent;
13 | import android.view.View;
14 | import android.view.WindowManager;
15 | import android.widget.ImageView;
16 | import android.widget.TextView;
17 |
18 | import com.pl.recent.MyApplication;
19 | import com.pl.recent.R;
20 |
21 | public class TipViewController implements View.OnClickListener, View.OnTouchListener {
22 | private static final String TAG="TipViewController";
23 |
24 | private static final int MOVETOEDGE=10010;
25 |
26 |
27 | private WindowManager mWindowManager;
28 | private Context mContext;
29 | private View mWholeView;
30 | private ImageView imageView;
31 | private TextView textView;
32 |
33 | private Handler mainHandler;
34 | private WindowManager.LayoutParams layoutParams;
35 | private float mTouchStartX,mTouchStartY;
36 | private int rotation;
37 | private boolean isMovingToEdge=false;
38 | private float density=0;
39 |
40 |
41 | private static class InnerClass {
42 | private static TipViewController instance = new TipViewController(MyApplication.getInstance());
43 | }
44 |
45 | public static TipViewController getInstance() {
46 | return InnerClass.instance;
47 | }
48 |
49 | private TipViewController(Context application) {
50 | mContext = application;
51 | mWindowManager = (WindowManager) application.getSystemService(Context.WINDOW_SERVICE);
52 | mainHandler=new Handler(Looper.getMainLooper()){
53 | @Override
54 | public void handleMessage(Message msg) {
55 | switch (msg.what){
56 | case MOVETOEDGE:
57 | int desX= (int) msg.obj;
58 | if (desX==0){
59 | layoutParams.x= (int) (layoutParams.x - density*10);
60 | if (layoutParams.x<0){
61 | layoutParams.x=0;
62 | }
63 | }else {
64 | layoutParams.x= (int) (layoutParams.x + density*10);
65 | if (layoutParams.x>desX){
66 | layoutParams.x=desX;
67 | }
68 | }
69 | updateViewPosition(layoutParams.x,layoutParams.y);
70 | if (layoutParams.x!=desX) {
71 | mainHandler.sendMessageDelayed(mainHandler.obtainMessage(MOVETOEDGE, desX),10);
72 | }else {
73 | isMovingToEdge = false;
74 |
75 | }
76 | break;
77 | }
78 | }
79 | };
80 | }
81 |
82 | public void show(final int floatType, final String time) {
83 |
84 | if (mWholeView!=null){
85 |
86 | mainHandler.post(new Runnable() {
87 | @Override
88 | public void run() {
89 | mWholeView.setVisibility(View.VISIBLE);
90 | textView.setText(time);
91 | switchFloat(floatType);
92 | if (rotation!=mWindowManager.getDefaultDisplay().getRotation()){
93 | moveToEdge();
94 | }
95 | }
96 | });
97 | return;
98 | }
99 |
100 | mWholeView = View.inflate(mContext, R.layout.view_float, null);
101 | imageView = (ImageView) mWholeView.findViewById(R.id.float_image);
102 | textView = (TextView) mWholeView.findViewById(R.id.float_text);
103 |
104 | switchFloat(floatType);
105 |
106 | DisplayMetrics displayMetrics=new DisplayMetrics();
107 | mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
108 | density=displayMetrics.density;
109 |
110 | // event listeners
111 | mWholeView.setOnTouchListener(this);
112 |
113 | int w = WindowManager.LayoutParams.WRAP_CONTENT;
114 | int h = WindowManager.LayoutParams.WRAP_CONTENT;
115 |
116 | int flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
117 | int type = 0;
118 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
119 | type = WindowManager.LayoutParams.TYPE_TOAST;
120 | } else {
121 | type = WindowManager.LayoutParams.TYPE_PHONE;
122 | }
123 |
124 |
125 | int width,height;
126 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
127 | Point point=new Point();
128 | mWindowManager.getDefaultDisplay().getSize(point);
129 | width=point.x;
130 | height=point.y;
131 | }else {
132 | width= mWindowManager.getDefaultDisplay().getWidth();
133 | height= mWindowManager.getDefaultDisplay().getHeight();
134 | }
135 | rotation = mWindowManager.getDefaultDisplay().getRotation();
136 | int x=0,y=0;
137 | x=width;
138 | y=height/2;
139 |
140 |
141 | layoutParams = new WindowManager.LayoutParams(w, h, type, flags, PixelFormat.TRANSLUCENT);
142 | layoutParams.gravity= Gravity.TOP| Gravity.LEFT;
143 | layoutParams.x=x;
144 | layoutParams.y=y;
145 |
146 | mainHandler.post(new Runnable() {
147 | @Override
148 | public void run() {
149 | try {
150 | mWindowManager.addView(mWholeView, layoutParams);
151 | } catch (Throwable e) {
152 | e.printStackTrace();
153 | }
154 | }
155 | });
156 | }
157 |
158 |
159 | public void hide(){
160 | mainHandler.post(new Runnable() {
161 | @Override
162 | public void run() {
163 | if (mWholeView!=null) {
164 | mWholeView.setVisibility(View.GONE);
165 | }
166 | }
167 | });
168 | }
169 |
170 | public void remove(){
171 | if (mWindowManager!=null&&mWholeView!=null) {
172 | try {
173 | mWindowManager.removeView(mWholeView);
174 | } catch (Throwable e) {
175 | e.printStackTrace();
176 | }
177 | }
178 | }
179 |
180 | public void switchFloat(int type){//type=1,图片,type=2,文字
181 | if (type==1){
182 | imageView.setVisibility(View.VISIBLE);
183 | textView.setVisibility(View.GONE);
184 | }else {
185 | imageView.setVisibility(View.GONE);
186 | textView.setVisibility(View.VISIBLE);
187 | }
188 | if (layoutParams!=null) {
189 | try {
190 | mWindowManager.updateViewLayout(mWholeView, layoutParams);
191 | } catch (Throwable e) {
192 | e.printStackTrace();
193 | }
194 | }
195 | }
196 |
197 | @Override
198 | public void onClick(View v) {
199 | }
200 |
201 | /**
202 | * touch the outside of the content view, remove the popped view
203 | */
204 | @Override
205 | public boolean onTouch(View v, MotionEvent event) {
206 | if (isMovingToEdge){
207 | return true;
208 | }
209 | float x = event.getRawX();
210 | float y = event.getRawY();
211 | switch (event.getAction()) {
212 | case MotionEvent.ACTION_DOWN:
213 | mTouchStartX = event.getX();
214 | mTouchStartY = event.getY();
215 | break;
216 | case MotionEvent.ACTION_MOVE:
217 | updateViewPosition(x,y);
218 | break;
219 | case MotionEvent.ACTION_UP:
220 | updateViewPosition(x,y);
221 | mTouchStartX = mTouchStartY = 0;
222 | moveToEdge();
223 | break;
224 | }
225 | return true;
226 | }
227 |
228 | private void updateViewPosition(float x,float y) {
229 | layoutParams.x = (int) (x - mTouchStartX);
230 | layoutParams.y = (int) (y - mTouchStartY);
231 | // layoutParams.x= (int) x;
232 | // layoutParams.y= (int) y;
233 | layoutParams.gravity=Gravity.TOP|Gravity.LEFT;
234 | try {
235 | mWindowManager.updateViewLayout(mWholeView, layoutParams);
236 | } catch (Throwable e) {
237 | e.printStackTrace();
238 | }
239 | }
240 |
241 | private void moveToEdge(){
242 | mainHandler.post(new Runnable() {
243 | @Override
244 | public void run() {
245 | isMovingToEdge=true;
246 | rotation=mWindowManager.getDefaultDisplay().getRotation();
247 | int width=0,height=0;
248 | int x=0,y=0;
249 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
250 | Point point=new Point();
251 | mWindowManager.getDefaultDisplay().getSize(point);
252 | width=point.x;
253 | height=point.y;
254 | }else {
255 | width= mWindowManager.getDefaultDisplay().getWidth();
256 |
257 | height= mWindowManager.getDefaultDisplay().getHeight();
258 | }
259 |
260 | int desX=0;
261 | if (layoutParams.x>width/2){
262 | desX=width;
263 | }else {
264 | desX=0;
265 | }
266 | mainHandler.sendMessage(mainHandler.obtainMessage(MOVETOEDGE,desX));
267 | }
268 | });
269 | }
270 |
271 | }
272 |
--------------------------------------------------------------------------------