================================================
FILE: README.md
================================================
FreeView
=============
FreeView create a floating view that you can use and move inside your app and also when your app is in background.
Usage
-----
Add library to your build.gradle:
```java
compile 'com.jcmore2.freeview:freeview:1.1.2'
```
Add Window permission in your manifest:
```xml
```
Init FreeView with your content:
```java
FreeView.init(MainActivity.this).withView(R.layout.content).showFreeView();
```
You can also use a callback:
```java
FreeView.init(MainActivity.this).withView(R.layout.content).showFreeView(new FreeView.FreeViewListener() {
@Override
public void onShow() {
Toast.makeText(MainActivity.this, "onShow", Toast.LENGTH_SHORT).show();
}
@Override
public void onDismiss() {
Toast.makeText(MainActivity.this, "onDismiss", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick() {
Toast.makeText(MainActivity.this, "onClick", Toast.LENGTH_SHORT).show();
}
});
```
Dismiss FreeView using:
```java
FreeView.get().dismissFreeView();
```
If you want FreeView will show when your app goes to background use ``dismissOnBackground(false)``:
```java
FreeView.init(MainActivity.this).withView(R.layout.content).dismissOnBackground(false).showFreeView(new FreeView.FreeViewListener() {
@Override
public void onShow() {
Toast.makeText(MainActivity.this, "onShow", Toast.LENGTH_SHORT).show();
}
@Override
public void onDismiss() {
Toast.makeText(MainActivity.this, "onDismiss", Toast.LENGTH_SHORT).show();
}
});
```
You can check the sample App!
Credits & Contact
-----------------
FreeView was created by jcmore2@gmail.com
License
-------
FreeView is available under the Apache License, Version 2.0.
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/app.iml
================================================
================================================
FILE: freeview/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Applications/adt-bundle-mac-x86_64-20130522/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
================================================
FILE: freeview/src/main/AndroidManifest.xml
================================================
================================================
FILE: freeview/src/main/java/com/jcmore2/freeview/BackgroundManager.java
================================================
package com.jcmore2.freeview;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class BackgroundManager implements Application.ActivityLifecycleCallbacks {
private static final String TAG = "BackgroundManager";
public static final long BACKGROUND_DELAY = 500;
private static BackgroundManager sInstance;
public interface Listener {
void onBecameForeground(Activity activity);
void onBecameBackground(Activity activity);
}
private boolean mInBackground = true;
private final List listeners = new ArrayList();
private final Handler mBackgroundDelayHandler = new Handler();
private Runnable mBackgroundTransition;
public static BackgroundManager init(Application application) {
if (sInstance == null) {
sInstance = new BackgroundManager(application);
}
return sInstance;
}
private BackgroundManager(Application application) {
application.registerActivityLifecycleCallbacks(this);
}
public static BackgroundManager get(){
if (sInstance == null) {
throw new IllegalStateException(
"BackgroundManager is not initialised - invoke " +
"at least once with parameterised init/get");
}
return sInstance;
}
public void registerListener(Listener listener) {
listeners.add(listener);
}
public void unregisterListener(Listener listener) {
listeners.remove(listener);
}
public boolean isInBackground() {
return mInBackground;
}
@Override
public void onActivityResumed(Activity activity) {
if (mBackgroundTransition != null) {
mBackgroundDelayHandler.removeCallbacks(mBackgroundTransition);
mBackgroundTransition = null;
}
if (mInBackground) {
mInBackground = false;
notifyOnBecameForeground(activity);
Log.i(TAG, "Application went to foreground");
}
}
private void notifyOnBecameForeground(Activity activity) {
for (Listener listener : listeners) {
try {
listener.onBecameForeground(activity);
} catch (Exception e) {
Log.e(TAG, "Listener threw exception!-->" + e);
}
}
}
@Override
public void onActivityPaused(final Activity activity) {
if (!mInBackground && mBackgroundTransition == null) {
mBackgroundTransition = new Runnable() {
@Override
public void run() {
mInBackground = true;
mBackgroundTransition = null;
notifyOnBecameBackground(activity);
Log.i(TAG, "Application went to background");
}
};
mBackgroundDelayHandler.postDelayed(mBackgroundTransition, BACKGROUND_DELAY);
}
}
private void notifyOnBecameBackground(Activity activity) {
for (Listener listener : listeners) {
try {
listener.onBecameBackground(activity);
} catch (Exception e) {
Log.e(TAG, "Listener threw exception!-->" + e);
}
}
}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
================================================
FILE: freeview/src/main/java/com/jcmore2/freeview/FreeView.java
================================================
package com.jcmore2.freeview;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by jcmore2 on 30/7/15.
*
* FreeView create a floating view that you can use inside and outside your app
*/
public class FreeView {
private static final String TAG = "FreeView";
private static Application application;
private static FreeView sInstance;
protected static Context mContext;
private static Intent service;
protected static FreeViewListener mListener;
protected static View contentView;
protected static boolean dismissOnBackground = true;
/**
* Init the FreeView instance
*
* @param context
*/
public static FreeView init(Context context) {
if (sInstance == null) {
sInstance = new FreeView(context);
}
return sInstance;
}
/**
* get the FreeView instance
* @return
*/
public static FreeView get(){
if (sInstance == null) {
throw new IllegalStateException(
"FreeView is not initialised - invoke " +
"at least once with parameterised init/get");
}
return sInstance;
}
/**
* Set respurce view
* @param resourceLayout
* @return
*/
public static FreeView withView(int resourceLayout){
LayoutInflater layoutInflater = (LayoutInflater) application.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = layoutInflater.inflate(resourceLayout, null);
return sInstance;
}
/**
* Set view
* @param view
* @return
*/
public static FreeView withView(View view){
contentView = view;
return sInstance;
}
/**
* Dismiss when app goes to background (Default true)
* @param dismiss
* @return
*/
public static FreeView dismissOnBackground(boolean dismiss){
dismissOnBackground = dismiss;
return sInstance;
}
/**
* Constructor
*
* @param context
*/
private FreeView(Context context) {
try {
if (context == null) {
Log.e(TAG, "Cant init, context must not be null");
} else {
mContext = context;
application = (Application) context.getApplicationContext();
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* Show view
*/
public static void showFreeView(){
showFreeView(null);
}
/**
* Show view with callback
*/
public static void showFreeView(FreeViewListener listener){
if(contentView == null)
throw new RuntimeException("It´ necessary call '.withView()' method");
mListener = listener;
service = new Intent(application, FreeViewService.class);
application.startService(service);
}
/**
* Dismiss View
*/
public static void dismissFreeView(){
if(service!=null)
application.stopService(service);
}
public interface FreeViewListener {
void onShow();
void onDismiss();
void onClick();
}
}
================================================
FILE: freeview/src/main/java/com/jcmore2/freeview/FreeViewService.java
================================================
package com.jcmore2.freeview;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
public class FreeViewService extends Service {
private static final String TAG = "FreeViewService";
private WindowManager windowManager;
private WindowManager.LayoutParams params;
private WindowManager.LayoutParams paramsF;
private View mView;
boolean isViewVisible = false;
/**
* Max allowed duration for a "click", in milliseconds.
*/
private static final int MAX_CLICK_DURATION = 1000;
/**
* Max allowed distance to move during a "click", in DP.
*/
private static final int MAX_CLICK_DISTANCE = 15;
private long pressStartTime;
private float pressedX;
private float pressedY;
private boolean stayedWithinClickDistance;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
createView();
BackgroundManager.init(getApplication()).registerListener(new BackgroundManager.Listener() {
@Override
public void onBecameForeground(Activity activity) {
}
@Override
public void onBecameBackground(Activity activity) {
if (FreeView.dismissOnBackground) {
removeView();
stopService();
}
}
});
}
/**
* Create view
*/
private void createView() {
mView = FreeView.contentView;
try {
mView.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
pressStartTime = System.currentTimeMillis();
pressedX = event.getX();
pressedY = event.getY();
stayedWithinClickDistance = true;
break;
case MotionEvent.ACTION_UP:
long pressDuration = System.currentTimeMillis() - pressStartTime;
if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
FreeView.mListener.onClick();
}
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
if (stayedWithinClickDistance && distance(pressedX, pressedY, event.getX(), event.getY()) > MAX_CLICK_DISTANCE) {
stayedWithinClickDistance = false;
}
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(mView, paramsF);
break;
}
return true;
}
});
} catch (Exception e) {
Log.e(TAG, "ON TOUCH ERROR--->" + e.getMessage());
}
setViewPosition();
addView();
}
private static float distance(float x1, float y1, float x2, float y2) {
float dx = x1 - x2;
float dy = y1 - y2;
float distanceInPx = (float) Math.sqrt(dx * dx + dy * dy);
return pxToDp(distanceInPx);
}
private static float pxToDp(float px) {
return px / FreeView.mContext.getResources().getDisplayMetrics().density;
}
/**
* Remove view from window
*/
private void removeView() {
Log.i(TAG, "removeView");
if (mView != null && isViewVisible) {
isViewVisible = false;
windowManager.removeView(mView);
if (FreeView.mListener != null) {
FreeView.dismissOnBackground = true;
FreeView.mListener.onDismiss();
}
}
}
/**
* Add view to window
*/
private void addView() {
Log.i(TAG, "addView");
if (mView != null && !isViewVisible) {
isViewVisible = true;
setViewPosition();
windowManager.addView(mView, params);
if (FreeView.mListener != null) {
FreeView.mListener.onShow();
}
}
}
/**
* Set initial position
*/
private void setViewPosition() {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER;
params.x = 0;
params.y = 0;
paramsF = params;
}
/**
* Stop service
*/
private void stopService() {
this.stopSelf();
}
@Override
public void onDestroy() {
super.onDestroy();
removeView();
}
}
================================================
FILE: freeview/src/main/res/values/strings.xml
================================================
FreeView
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Thu Jul 30 15:42:42 CEST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: settings.gradle
================================================
include ':app', ':freeview'