├── .gitignore
├── README.md
├── build.gradle
├── example
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── io
│ │ └── eisner
│ │ └── bannerads
│ │ └── MainActivity.java
│ └── res
│ ├── layout
│ ├── activity_main.xml
│ └── content_main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ ├── values-v21
│ └── styles.xml
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── build.gradle
├── libs
│ ├── okhttp-2.5.0.jar
│ └── okio-1.6.0.jar
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── io
│ │ └── eisner
│ │ └── ads
│ │ ├── Ad.java
│ │ ├── AdCache.java
│ │ ├── AdParser.java
│ │ ├── AdProvider.java
│ │ ├── GetResponse.java
│ │ └── HeaderFields.java
│ └── res
│ ├── drawable
│ └── placeholder.png
│ └── values
│ └── values.xml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Android template
3 | # Built application files
4 | *.apk
5 | *.ap_
6 |
7 | # Files for the Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 |
17 | # Gradle files
18 | .gradle/
19 | build/
20 |
21 | # Local configuration file (sdk path, etc)
22 | local.properties
23 |
24 | # Proguard folder generated by Eclipse
25 | proguard/
26 |
27 | # Log Files
28 | *.log
29 |
30 | # Android Studio Navigation editor temp files
31 | .navigation/
32 | /example/src/main/res/values/keyinfo.xml
33 |
34 | .DS_Store
35 | *.iml
36 | /.idea
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AndroidAds (Beta)
2 | A simple Android library that allows an ad slideshow to be added into any view in your app. This allows you to host and control your own ads. Your server sends out a XML response and the `AdProvider` parses that XML, looking for urls located in the set `.parseTag`.
3 |
4 | # Start Here
5 |
6 | [](https://jitpack.io/#nateisner/android-ads/)
7 |
8 | You must first add JitPack.io to the repositories list in your app's build.gradle file:
9 |
10 | ```gradle
11 | repositories {
12 | maven { url "https://jitpack.io" }
13 | }
14 | ```
15 |
16 | Then, add this to the list of dependencies:
17 |
18 | ```gradle
19 | dependencies {
20 | compile 'com.github.nateisner:android-ads:0.1.1'
21 | }
22 | ```
23 | ## Usage
24 |
25 | Add a `ViewGroup` to your layout that will act as the root for the images. This can be a `RelativeLayout`, `LinearLayout`, `CoordinatorLayout` ...etc. The sizes of this view will be the size of the ads shown.
26 |
27 | Example:
28 |
29 |
30 | ```
31 |
36 | ```
37 |
38 |
39 | Then, you can build your `AdProvider`. Using supported features.
40 |
41 | ```
42 | new AdProvider.Builder(context)
43 | .imageServer(serverStringURL)
44 | .parseTag("imagefilename")
45 | .attachTo(rootView)
46 | .imageTime(5000) //in ms
47 | .useAPIKey(keyserver, keyheaders, keyHeaderName)
48 | .start();
49 | ```
50 |
51 |
52 | Features include:
53 |
54 | * Additional HeaderFields can be added for use when making the XML request.
55 |
56 | `HeaderFields` object is used to add fields to any HTTP request made by your `AdProvider` Example:
57 |
58 | ```
59 | HeaderFields moreheaders = new HeaderFields();
60 | moreheaders.add("X-FieldName1","value");
61 | moreheaders.add("X-FieldName2","valueofanother");
62 | ```
63 |
64 | `.requestHeader(HeaderField moreheaders)`
65 |
66 | * A Placeholder for when images are loading or cannot be found.
67 |
68 | `.placeholder(Drawable)`
69 |
70 |
71 | * The disk cache size can be increased or decreased. The default is set to 6 images if the xml has more than the amount set, it will attempt to load from server once it reaches the max on disk.
72 |
73 | `.cacheSize(int size)`
74 |
75 | * Offline mode will enable your app to use what ever images it has cached on disk if there is no connection with the server. The images that will be shown are the last images that were cached and hopefully not cleared by the system or user. (This feature is not fully implemented yet)
76 |
77 | `.offlineUse(true)`
78 |
79 | ## How It Works
80 |
81 | #### Your Ad Server
82 |
83 | * You must have a backend server that hosts all of your images and generates a list of the images in a XML ~~or JSON~~ response
84 | * The response is structured something like this:
85 |
86 | ```
87 |
88 |
89 | 11
90 | Title
91 | This is an album full of ...
92 |
93 |
94 | 26
95 | Desc of image
96 | Title
97 | http://yourserver.com/561c3c48293d09.81340072/561c3daca3c06.png
98 |
99 |
100 | 27
101 | Desc of image
102 | Title
103 | http://yourserver.com/561c3c48293d09.81340072/561c3dc5c1413.png
104 |
105 |
106 |
107 | ```
108 | The internal parser parses through the XML for a `.parseTag` that is set when building your `AdProvider`. In this example you would set `.parseTag` to "imagefilename".
109 |
110 | * API Key - Sometimes you may want to limit your server's access by using an API key in your HTTP request header. The `AdProvider` can be built with `.useAPIKey()`. Such as:
111 |
112 | ```
113 | //HeaderFields object that maybe needed to get the response
114 | HeaderFields keyheaders = new HeaderFields();
115 | keyheaders.add("X-FIELD-NAME", "value");
116 |
117 | //String of the url that will repond with the key
118 | String keyserver = "http://www.apikeyserver.com";
119 |
120 | //String name of the HeaderField the key is used in the XML request.
121 | String keyHeaderField = "X-API-KEY";
122 |
123 | .useAPIKey(keyserver, keyheaders, keyHeaderField);
124 | ```
125 | The server should respond with `
126 |
127 | - keyvaluehere
128 | ` and that key value will be used for the rest of the session.
129 |
130 | #### Your App
131 |
132 | * The main purpose of this library is to simplify a way to insert ads into your app. By using `.attachTo` to insert ads in a `ViewGroup`. This will be a set `View` that you can either programmatically implement or add into your layout's XML. In the example, I have attached the ads in a `RelativeLayout` and set the parameters to specify location and size. The images will crop and fit inside of that view.
133 | * The `AdProvider` has a `stop()` and `restart()` methods that can be used in your activity's `onStop()` or `onResume()` if you don't want the AdProvider to continue to (attempt) run in the background.
134 | * The file cache holds images until cleared by the system or the user. (or overwritten by new instance of this library) This will allow displaying ads with no network connectivity and saving battery by bulk loading. The file cache can be limited if space is an issue but that will mean if `AdProvider` runs into an un-cached image in its list, it will attempt to load that image from the network and delete one from the cache to hold true to the cache limit.
135 | * ~~Image limit can be set for how many images you would like to grab from the list of images given by the server~~ Not yet...
136 |
137 | ## Future
138 |
139 | * Features in the works
140 | * Total image limit - limit amount grabbed from the server's list response.
141 | * JSON support
142 | * Performance enhancements
143 | * Different animation types for image slideshow
144 | * ???
145 |
146 | ## Developed By
147 |
148 | * Nate Eisner - nate@eisner.io
149 |
150 | ## License
151 |
152 | ```
153 | Copyright 2015 Nathan Eisner
154 |
155 | Licensed under the Apache License, Version 2.0 (the "License");
156 | you may not use this file except in compliance with the License.
157 | You may obtain a copy of the License at
158 |
159 | http://www.apache.org/licenses/LICENSE-2.0
160 |
161 | Unless required by applicable law or agreed to in writing, software
162 | distributed under the License is distributed on an "AS IS" BASIS,
163 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
164 | See the License for the specific language governing permissions and
165 | limitations under the License.
166 | ```
167 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:1.2.3'
9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
10 | }
11 | }
12 |
13 | allprojects {
14 | repositories {
15 | jcenter()
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/example/.gitignore:
--------------------------------------------------------------------------------
1 | /src/main/res/values/keyinfo.xml
2 | /build
3 |
--------------------------------------------------------------------------------
/example/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.1"
6 |
7 | defaultConfig {
8 | applicationId "io.eisner.bannerads"
9 | minSdkVersion 17
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
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 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.1.0'
26 | compile 'com.android.support:design:23.1.0'
27 | compile project(':library')
28 | }
29 |
--------------------------------------------------------------------------------
/example/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 /Volumes/Storage/android/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 |
--------------------------------------------------------------------------------
/example/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
13 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/example/src/main/java/io/eisner/bannerads/MainActivity.java:
--------------------------------------------------------------------------------
1 | package io.eisner.bannerads;
2 |
3 | import android.os.Bundle;
4 | import android.support.design.widget.FloatingActionButton;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.support.v7.widget.Toolbar;
7 | import android.view.View;
8 | import android.widget.Toast;
9 |
10 | import io.eisner.ads.AdProvider;
11 | import io.eisner.ads.HeaderFields;
12 |
13 | public class MainActivity extends AppCompatActivity {
14 | private FloatingActionButton fab;
15 | AdProvider myAdProvider;
16 |
17 | @Override
18 | protected void onCreate(Bundle savedInstanceState) {
19 | super.onCreate(savedInstanceState);
20 | setContentView(R.layout.activity_main);
21 |
22 | String keyserver = getResources().getString(R.string.server);
23 | String key = getResources().getString(R.string.key);
24 | String secret = getResources().getString(R.string.secret);
25 |
26 | HeaderFields keyheaders = new HeaderFields();
27 | keyheaders.add("X-API-KEY",key);
28 | keyheaders.add("X-SHHH-ITS-A-SECRET",secret);
29 | String keyHeaderName = "X-API-KEY";
30 |
31 | View rootView = findViewById(R.id.adContainer);
32 |
33 | final String server = getResources().getString(R.string.xmlserver);
34 |
35 | myAdProvider = new AdProvider.Builder(this)
36 | .imageServer(server) //the location of the xml
37 | .attachTo(rootView) //root to attach to, the height
38 | .imageTime(5000) //in ms
39 | .parseTag("imagefilename") //tag in the xml where the images are wrapped in
40 | .offlineUse(true) //if there is no connectivity the device will used the local ads
41 | .useAPIKey(keyserver, keyheaders, keyHeaderName) //setup if an api key is needed
42 | // in xml request
43 | .start();
44 |
45 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
46 | setSupportActionBar(toolbar);
47 |
48 | fab = (FloatingActionButton) findViewById(R.id.fab);
49 | fab.setOnClickListener(new View.OnClickListener() {
50 | @Override
51 | public void onClick(View view) {
52 | Toast.makeText(getApplicationContext(),"Button Pressed",Toast.LENGTH_SHORT).show();
53 | }
54 | });
55 | }
56 |
57 | private void hideFab() {
58 | fab.animate()
59 | .setDuration(1200)
60 | .translationY(500)
61 | .start();
62 | }
63 |
64 | @Override
65 | protected void onStop() {
66 | super.onStop();
67 | // myAdProvider.stop();
68 | }
69 |
70 | @Override
71 | protected void onPause() {
72 | super.onPause();
73 | // myAdProvider.stop();
74 | }
75 |
76 | @Override
77 | protected void onResume() {
78 | super.onResume();
79 | // myAdProvider.restart();
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/example/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
15 |
16 |
22 |
23 |
24 |
25 |
26 |
27 |
32 |
33 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/example/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/example/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/example/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/example/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/example/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/example/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 | >
2 |
8 |
9 |
--------------------------------------------------------------------------------
/example/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BannerAds
3 | MainActivity
4 |
5 |
--------------------------------------------------------------------------------
/example/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/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 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Nov 01 23:13:11 CST 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.8-bin.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | group='com.github.nateisner'
4 |
5 | android {
6 | compileSdkVersion 22
7 | buildToolsVersion "22.0.1"
8 |
9 | defaultConfig {
10 | minSdkVersion 14
11 | targetSdkVersion 22
12 | versionCode 1
13 | versionName "0.1"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | compile fileTree(dir: 'libs', include: ['*.jar'])
25 | testCompile 'junit:junit:4.12'
26 | compile 'com.android.support:support-annotations:22.+'
27 | compile 'com.android.support:appcompat-v7:22.+'
28 | compile files('libs/okhttp-2.5.0.jar')
29 | compile files('libs/okio-1.6.0.jar')
30 | compile files('libs/android-support-design.jar')
31 | }
32 |
33 | // build a jar with source files
34 | task sourcesJar(type: Jar) {
35 | from android.sourceSets.main.java.srcDirs
36 | classifier = 'sources'
37 | }
38 |
39 | task javadoc(type: Javadoc) {
40 | failOnError false
41 | source = android.sourceSets.main.java.sourceFiles
42 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
43 | }
44 |
45 | // build a jar with javadoc
46 | task javadocJar(type: Jar, dependsOn: javadoc) {
47 | classifier = 'javadoc'
48 | from javadoc.destinationDir
49 | }
50 |
51 | artifacts {
52 | archives sourcesJar
53 | archives javadocJar
54 | }
55 |
56 | // uncomment to build a jar file in addition to the default aar file
57 | //android.libraryVariants.all { variant ->
58 | // def name = variant.buildType.name
59 | // def task = project.tasks.create "jar${name.capitalize()}", Jar
60 | // task.dependsOn variant.javaCompile
61 | // task.from variant.javaCompile.destinationDir
62 | // artifacts.add('archives', task);
63 | //}
64 |
65 | dependencies {
66 | compile 'com.android.support:support-v4:23.1.0'
67 | }
--------------------------------------------------------------------------------
/library/libs/okhttp-2.5.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/library/libs/okhttp-2.5.0.jar
--------------------------------------------------------------------------------
/library/libs/okio-1.6.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/library/libs/okio-1.6.0.jar
--------------------------------------------------------------------------------
/library/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 /Volumes/Storage/android/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 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/library/src/main/java/io/eisner/ads/Ad.java:
--------------------------------------------------------------------------------
1 | package io.eisner.ads;
2 |
3 | import android.content.Context;
4 | import android.support.v4.content.ContextCompat;
5 | import android.view.ViewGroup;
6 | import android.widget.ImageView;
7 | import android.widget.RelativeLayout;
8 |
9 | /**
10 | * An ad view that is added into the root view
11 | * Created by nathan eisner on 10/5/15.
12 | */
13 | public class Ad extends ImageView {
14 | public Ad(Context context) {
15 | super(context);
16 | RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
17 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
18 | layoutParams.alignWithParent = true;
19 | layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
20 | setScaleType(ScaleType.FIT_CENTER);
21 | setLayoutParams(layoutParams);
22 | // setBackgroundColor(Color.CYAN);
23 | setVisibility(VISIBLE);
24 | setImageDrawable(ContextCompat.getDrawable(context,R.drawable.placeholder));
25 | // addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
26 | // @Override
27 | // public void onViewAttachedToWindow(View v) {
28 | // View viewParent = (View) getParent();
29 | // View grandParent = (View) viewParent.getParent();
30 | // if (grandParent instanceof RelativeLayout) {
31 | // Log.i("AdView", "GrandParent is RelativeLayout");
32 | // } else if (viewParent instanceof LinearLayout) {
33 | // Log.i("AdView", "GrandParent is LinearLayout");
34 | // }
35 | // }
36 | //
37 | // @Override
38 | // public void onViewDetachedFromWindow(View v) {
39 | //
40 | // }
41 | // });
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/library/src/main/java/io/eisner/ads/AdCache.java:
--------------------------------------------------------------------------------
1 | package io.eisner.ads;
2 |
3 | import android.content.Context;
4 | import android.util.Log;
5 |
6 | import com.squareup.okhttp.Request;
7 |
8 | import java.io.File;
9 | import java.io.FileOutputStream;
10 | import java.io.IOException;
11 | import java.util.ArrayList;
12 |
13 | /**
14 | * A class that caches images to disk
15 | * The limit of images stored on disk can be changed
16 | * Created by nathan eisner
17 | */
18 | public class AdCache {
19 | private static String dir;
20 | private static final String TAG = "AdCache";
21 | private static ArrayList urls = new ArrayList<>();
22 | private int limit;
23 | private int cacheCount;
24 |
25 | /**
26 | * Constructor with setting cache limit
27 | *
28 | * @param context the context to which the AdProvider is running on
29 | */
30 | public AdCache(Context context, int limit) {
31 | this.limit = limit;
32 | initialize(context);
33 | }
34 |
35 | /**
36 | * Initialize the cache directory and clear old cache is exists
37 | *
38 | * @param context the context to which the AdProvider is running on
39 | */
40 | private void initialize(Context context) {
41 | dir = context.getFilesDir().getAbsolutePath() + "/ads";
42 | File folder = new File(dir);
43 | if (!folder.exists()) {
44 | folder.mkdir();
45 | } else {
46 | //clear cache
47 | File[] files = folder.listFiles();
48 | for (File file : files) {
49 | file.delete();
50 | }
51 | }
52 | }
53 |
54 | /**
55 | * Amount of ads in cache
56 | *
57 | * @return int number of ads
58 | */
59 | public int getCacheSize() {
60 | return urls.size();
61 | }
62 |
63 | /**
64 | * Cache the response from the server until limit is hit then just save the url
65 | *
66 | * @param url the location of the response to cache
67 | */
68 | public void cache(String url) {
69 | if (cacheCount < limit) {
70 | Request request = new Request.Builder()
71 | .url(url)
72 | .build();
73 | try {
74 | byte[] bytes = GetResponse.forBytes(request);
75 | if (bytes.length != 0) {
76 | FileOutputStream fo = new FileOutputStream(dir + "/" + urls.size());
77 | urls.add(url);
78 | fo.write(bytes);
79 | fo.close();
80 | cacheCount++;
81 | }
82 | } catch (IOException e) {
83 | e.printStackTrace();
84 | }
85 |
86 | } else {
87 | urls.add(url);
88 | }
89 | }
90 |
91 | /**
92 | * Internal cache for a saved url
93 | *
94 | * @param position position in the url list to cache
95 | */
96 | private boolean cache(int position) {
97 | if (urls != null && !urls.isEmpty()) {
98 | String url = urls.get(position);
99 | if (url != null && !url.isEmpty()) {
100 | Request request = new Request.Builder()
101 | .url(url)
102 | .build();
103 | try {
104 | byte[] bytes = GetResponse.forBytes(request);
105 | if (bytes.length != 0) {
106 | FileOutputStream fo = new FileOutputStream(dir + "/" + position);
107 | fo.write(bytes);
108 | fo.close();
109 | cacheCount++;
110 | } else {
111 | Log.i(TAG, "Image is empty");
112 | }
113 | } catch (IOException e) {
114 | e.printStackTrace();
115 | }
116 | return true;
117 | }
118 | } else {
119 |
120 | Log.i(TAG, "no urls");
121 |
122 | }
123 | return false;
124 | }
125 |
126 | /**
127 | * To retrieve an ad from the cache. If not cached, cache and try to retrieve
128 | * If that fails then
129 | * Also, caches next file for quicker loading.
130 | *
131 | * @param position the position of the ad in the cache
132 | * @return Path of the file
133 | */
134 | public String retrieve(int position) {
135 | File image = new File(dir + "/" + position);
136 | if (!image.exists()) {
137 | if (cache(position)) {
138 | removeLeastUsed(position);
139 | retrieve(position);
140 | } else {
141 | return retrieve(position ++);
142 | }
143 | }
144 | //// TODO: 11/1/15 fix looping issue
145 | // //cache next one
146 | // int next = position + 1;
147 | // //are we at the last image?
148 | // if (next >= urls.size()) {
149 | // //loop to first again
150 | // next = 0;
151 | // }
152 | // File nextImage = new File(dir + "/" + next);
153 | // if (!nextImage.exists()) {
154 | // final int finalNext = next;
155 | // new Thread(new Runnable() {
156 | // @Override
157 | // public void run() {
158 | // if ;
159 | // }
160 | // }).start();
161 | // }
162 | return image.getAbsolutePath();
163 | }
164 |
165 | /**
166 | * Deleting of the furthest possible cached image away from current position if we are over
167 | * the limit
168 | *
169 | * @param currentPos position of the current image
170 | */
171 | public void removeLeastUsed(int currentPos) {
172 | int leastPos = currentPos - limit;
173 | if (leastPos < 0) {
174 | leastPos = urls.size() + leastPos;
175 | }
176 | File file = new File(dir + "/" + leastPos);
177 | if (file.exists()) {
178 | if (file.delete())
179 | cacheCount--;
180 | else
181 | Log.e(TAG, "File did not delete from cache");
182 | }
183 | }
184 |
185 | public boolean isEmpty() {
186 | return getCacheSize() == 0;
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/library/src/main/java/io/eisner/ads/AdParser.java:
--------------------------------------------------------------------------------
1 | package io.eisner.ads;
2 |
3 | import org.xmlpull.v1.XmlPullParser;
4 | import org.xmlpull.v1.XmlPullParserException;
5 | import org.xmlpull.v1.XmlPullParserFactory;
6 |
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * Parses XML to get image urls
13 | * Created by nathan eisner
14 | */
15 | public class AdParser {
16 |
17 | /**
18 | * Parses XML file to get ad uris
19 | *
20 | * @param inputStream the xml response from server
21 | * @return ArrayList of ad uris
22 | */
23 | public static ArrayList parseForImages(InputStream inputStream, String aTagName) {
24 | return parse(inputStream, aTagName);
25 | }
26 |
27 | /**
28 | * Used to find the API key in a response in the tags - KEY HERE
29 | *
30 | * @param inputStream the response body as byte stream
31 | * @return found key or empty if no key
32 | */
33 | public static String parseForKey(InputStream inputStream) {
34 | return parse(inputStream, "item").get(0);
35 | }
36 |
37 | /**
38 | * Internal parse that uses XMLPullParser to find text located inside of tagToFind
39 | *
40 | * @param inputStream the XML file that is being parsed
41 | * @param tagToFind the tag that the parser will look for
42 | * @return an ArrayList of Strings found within the given tag name
43 | */
44 | private static ArrayList parse(InputStream inputStream, String tagToFind) {
45 | ArrayList result = new ArrayList<>();
46 | XmlPullParserFactory factory;
47 | XmlPullParser parser;
48 | try {
49 | factory = XmlPullParserFactory.newInstance();
50 | factory.setNamespaceAware(true);
51 | parser = factory.newPullParser();
52 | parser.setInput(inputStream, null);
53 | int eventType = parser.getEventType();
54 | while (eventType != XmlPullParser.END_DOCUMENT) {
55 | String tagName = parser.getName();
56 | if (tagName != null && tagName.equalsIgnoreCase(tagToFind)) {
57 | parser.next();
58 | String text = parser.getText();
59 | if (text != null && !text.isEmpty()) {
60 | result.add(text);
61 | }
62 | }
63 | eventType = parser.next();
64 | }
65 | } catch (XmlPullParserException | IOException e) {
66 | e.printStackTrace();
67 | }
68 | return result;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/library/src/main/java/io/eisner/ads/AdProvider.java:
--------------------------------------------------------------------------------
1 | package io.eisner.ads;
2 |
3 | import android.animation.Animator;
4 | import android.content.Context;
5 | import android.graphics.Bitmap;
6 | import android.graphics.BitmapFactory;
7 | import android.graphics.drawable.Drawable;
8 | import android.os.AsyncTask;
9 | import android.os.Handler;
10 | import android.support.annotation.NonNull;
11 | import android.support.annotation.Nullable;
12 | import android.util.Log;
13 | import android.view.View;
14 | import android.view.ViewGroup;
15 |
16 | import com.squareup.okhttp.Request;
17 |
18 | import java.io.InputStream;
19 | import java.util.ArrayList;
20 | import java.util.Set;
21 | import java.util.concurrent.ExecutionException;
22 |
23 | /**
24 | * The main provider that gets ads and controls the image view contents
25 | * Builder builds all of the options for the provider
26 | *
27 | * Created by nathan eisner
28 | */
29 | public class AdProvider {
30 | protected final String TAG = "AdProvider";
31 | protected final Builder myBuilder;
32 | protected boolean initialized = false;
33 | protected boolean startWhenReady = false;
34 | //current ad displayed
35 | protected int adNum = 0;
36 | protected Ad adView;
37 | protected AdCache adCache;
38 | protected String keyValue = "";
39 | protected boolean networkIsLoading = true;
40 | protected boolean hasAtLeastOne = false;
41 | protected Handler handleImageLoad = new Handler();
42 | protected Runnable imageRunnable = new Runnable() {
43 | @Override
44 | public void run() {
45 | if (!adCache.isEmpty()) {
46 | //zero indexed so max = size-1 NO OFFBYZERO!
47 | if (adNum == adCache.getCacheSize() - 1) {
48 | adNum = 0;
49 | } else {
50 | adNum++;
51 | }
52 | setImage(adNum);
53 | }
54 | handleImageLoad.postDelayed(this, myBuilder.delay);
55 | }
56 | };
57 |
58 | private AdProvider(Builder builder) {
59 | this.myBuilder = builder;
60 | adView = new Ad(myBuilder.context);
61 | myBuilder.rootView.addView(adView);
62 | adCache = new AdCache(myBuilder.context, myBuilder.cacheAmt);
63 | if (myBuilder.drawablePlaceholder != null) {
64 | adView.setImageDrawable(myBuilder.drawablePlaceholder);
65 | }
66 | if (myBuilder.usingKey) {
67 | getAPIKey(myBuilder.keyServer, myBuilder.keyHeaders);
68 | } else {
69 | getAds();
70 | }
71 | }
72 |
73 | /**
74 | * To get the current builder of this provider
75 | * @return the builder
76 | */
77 | public final Builder getBuilder() {
78 | return myBuilder;
79 | }
80 |
81 | /**
82 | * Class to build an AdProvider using a various amount of options
83 | */
84 | public static class Builder {
85 | protected final Context context;
86 | protected String server;
87 | protected String xmlTag;
88 | protected String key;
89 | protected ViewGroup rootView = null;
90 | protected boolean useOffline;
91 | protected long delay;
92 | protected Drawable drawablePlaceholder = null;
93 | protected HeaderFields headers = new HeaderFields();
94 | protected int cacheAmt;
95 | protected boolean usingKey;
96 | protected String keyServer;
97 | protected HeaderFields keyHeaders;
98 | protected String keyHeaderName;
99 |
100 | public Builder(@NonNull Context context) {
101 | //default values
102 | this.context = context;
103 | this.delay = 10000;
104 | this.useOffline = true;
105 | this.xmlTag = "imagefilename";
106 | this.key = null;
107 | this.cacheAmt = 6;
108 | this.usingKey = false;
109 | }
110 |
111 | public Builder imageServer(@NonNull String path) {
112 | this.server = path;
113 | return this;
114 | }
115 |
116 | public Builder requestHeader(@NonNull HeaderFields addHeaders) {
117 | this.headers = addHeaders;
118 | return this;
119 | }
120 |
121 | public Builder useAPIKey(@NonNull String server, @Nullable HeaderFields headers,
122 | @NonNull String name) {
123 | this.keyServer = server;
124 | this.keyHeaders = headers;
125 | this.keyHeaderName = name;
126 | this.usingKey = true;
127 | return this;
128 | }
129 |
130 | public Builder imageTime(@NonNull long time) {
131 | this.delay = time;
132 | return this;
133 | }
134 |
135 | public Builder attachTo(@NonNull View root) {
136 | if (root instanceof ViewGroup) {
137 | this.rootView = (ViewGroup) root;
138 | return this;
139 | }
140 | throw new IllegalArgumentException("A ViewGroup type is needed to attach to");
141 | }
142 |
143 | public Builder parseTag(@NonNull String tagname) {
144 | this.xmlTag = tagname;
145 | return this;
146 | }
147 |
148 | public Builder offlineUse(boolean option) {
149 | this.useOffline = option;
150 | return this;
151 | }
152 |
153 | public Builder cacheSize(int num) {
154 | this.cacheAmt = num;
155 | return this;
156 | }
157 |
158 | public Builder placeholder(Drawable drawable) {
159 | this.drawablePlaceholder = drawable;
160 | return this;
161 | }
162 |
163 | public AdProvider build() {
164 | if (this.rootView != null)
165 | return new AdProvider(this);
166 | throw new IllegalStateException("Root view cannot be null");
167 | }
168 |
169 | public AdProvider start() {
170 | AdProvider ap = build();
171 | ap.start();
172 | return ap;
173 | }
174 |
175 | }
176 |
177 | //// TODO: 10/19/15 NEED TO HANDLE NO NETWORK CONNECTIVITY
178 | // Have a Default Ad image load if no network connectivity?
179 | // or Load old ads if no current network connection
180 |
181 | /**
182 | * Start showing ads into root view
183 | */
184 | public void start() {
185 | if (!networkIsLoading) {
186 | setImage(0);
187 | handleImageLoad.postDelayed(imageRunnable, myBuilder.delay);
188 | } else {
189 | startWhenReady = true;
190 | }
191 | }
192 |
193 | /**
194 | * If background loading of ads is not needed then stopping the provider can be done
195 | */
196 | public void stop() {
197 | handleImageLoad.removeCallbacks(imageRunnable);
198 | Log.d(TAG, "Stopped");
199 | }
200 |
201 | /**
202 | * If a restart of the provider is needed...ex onResume of Activity
203 | */
204 | public void restart() {
205 | handleImageLoad.removeCallbacks(imageRunnable);
206 | if (initialized) {
207 | Log.d(TAG, "Restarted");
208 | start();
209 | }
210 | }
211 |
212 | /**
213 | * Check for a 204 response from Google server to verify network connectivity
214 | *
215 | * @return true if the network is connected
216 | */
217 | public static boolean isConnected() {
218 | Request request = new Request.Builder()
219 | .get()
220 | .url("http://clients3.google.com/generate_204")
221 | .build();
222 | return GetResponse.forOK(request);
223 | }
224 |
225 | /**
226 | * Handles building a OkHttp Request with a dynamic collection of header information
227 | *
228 | * @param url the server url where the request is being made to
229 | * @param headerFields a collection of names and values needed to make request
230 | * @return the built Request
231 | */
232 | public static Request buildARequest(@NonNull String url,
233 | @Nullable HeaderFields headerFields) {
234 | Request.Builder builder = new Request.Builder();
235 | builder.get()
236 | .url(url);
237 |
238 | if (headerFields != null) {
239 | Set headers = headerFields.getNameSet();
240 | if (headers != null && !headers.isEmpty()) {
241 | for (String header : headers) {
242 | builder.addHeader(header, headerFields.getValue(header));
243 | }
244 | }
245 | }
246 |
247 | return builder.build();
248 | }
249 |
250 | /**
251 | * This is used to get an API Key from a server if one is needed to insert in the GET header
252 | * Saves key into a stored variable and is used to GET xml of all image urls
253 | *
254 | * @param url used in GET that returns the API key
255 | * @param headers Headers to add to the request for the API key
256 | */
257 | private String getAPIKey(String url, @Nullable HeaderFields headers) {
258 | Request request = buildARequest(url, headers);
259 | networkIsLoading = true;
260 | if (isConnected()) {
261 | try {
262 | return new GetAPIKey().execute(request).get();
263 | } catch (InterruptedException | ExecutionException e) {
264 | e.printStackTrace();
265 | }
266 | }
267 | return "";
268 | }
269 |
270 | /**
271 | * Task to get the api key from a server. Starts to get ads when key is received
272 | */
273 | private class GetAPIKey extends AsyncTask {
274 |
275 | @Override
276 | protected String doInBackground(Request... params) {
277 | InputStream is = GetResponse.forStream(params[0]);
278 | if (is != null) {
279 | return AdParser.parseForKey(is);
280 | }
281 | Log.e("API Key", "key response null");
282 | return "";
283 | }
284 |
285 | @Override
286 | protected void onPostExecute(String s) {
287 | keyValue = s;
288 | getAds();
289 | }
290 | }
291 |
292 | /**
293 | * Starts the get ads task based off of some certain parameters
294 | */
295 | public void getAds() {
296 | if (isConnected() && (myBuilder.usingKey && !keyValue.equals(""))) {
297 | new GetAdsTask().execute();
298 | } else {
299 | //// TODO: 10/30/15 try again sometime?? use cached ads??
300 | //if offline mode enabled use cached local ads
301 | //else nothing is shown or placeholder is shown if added
302 | }
303 | }
304 |
305 | /**
306 | * Task to get ads from server and to load each ad in the cache
307 | */
308 | protected class GetAdsTask extends AsyncTask {
309 | @Override
310 | protected void onPreExecute() {
311 | super.onPreExecute();
312 | networkIsLoading = true;
313 | }
314 |
315 | @Override
316 | protected void onPostExecute(Boolean aBoolean) {
317 | networkIsLoading = aBoolean;
318 | if (startWhenReady) {
319 | start();
320 | }
321 | }
322 |
323 | @Override
324 | protected void onProgressUpdate(String... values) {
325 | super.onProgressUpdate(values);
326 | }
327 |
328 | @Override
329 | protected Boolean doInBackground(Void... params) {
330 | Log.d(TAG, "Starting to get ads");
331 | if (myBuilder.usingKey) {
332 | myBuilder.headers.add(myBuilder.keyHeaderName, keyValue);
333 | }
334 | Request request = buildARequest(myBuilder.server, myBuilder.headers);
335 | Log.d("Request", request.toString());
336 | ArrayList ads = null;
337 | long start = System.currentTimeMillis();
338 | InputStream is = GetResponse.forStream(request);
339 | Log.d("time for response", "" + (start - System.currentTimeMillis()));
340 | if (is != null) {
341 | // start = System.currentTimeMillis();
342 | ads = AdParser.parseForImages(is, myBuilder.xmlTag);
343 | // Log.d("time for parse", "" + (start - System.currentTimeMillis()));
344 | } else {
345 | Log.e(TAG, "Response was not good...");
346 | }
347 | //cache ads
348 | if (ads != null && !ads.isEmpty()) {
349 | for (String uri : ads) {
350 | adCache.cache(uri);
351 | hasAtLeastOne = true;
352 | }
353 | }
354 | Log.d(TAG, "Done with ads");
355 | return false;
356 | }
357 | }
358 |
359 | /**
360 | * Starts the task to load image into the ad view depending on some logic
361 | *
362 | * @param imageId the position of the ad that was cached
363 | */
364 | private void setImage(final int imageId) {
365 | if (adView != null) {
366 | boolean hasNetwork = isConnected();
367 | if (!networkIsLoading && hasNetwork) {
368 | new SetImageTask().execute(imageId);
369 | //// TODO: 11/1/15 VVV Handle different loading situations VVV
370 | // } else if (hasAtLeastOne) {
371 | // //load first image
372 | // Log.d("SetImage", "has at least one image");
373 | // } else if (!hasNetwork) {
374 | // Log.d("SetImage", "no network");
375 | // adView.setAlpha(0f);
376 | // adView.setVisibility(View.VISIBLE);
377 | // adView.animate()
378 | // .alpha(1f)
379 | // .setDuration(1500)
380 | // .setListener(null);
381 | // } else {
382 | // Log.d("SetImage", "nothing...");
383 | //// progressBar.setVisibility(View.VISIBLE);
384 |
385 | }
386 | }
387 | }
388 |
389 | /**
390 | * Task to get the Bitmap from the cache and animate the bitmap in the ad view
391 | */
392 | protected class SetImageTask extends AsyncTask {
393 | @Override
394 | protected Bitmap doInBackground(Integer... params) {
395 | return BitmapFactory.decodeFile(adCache.retrieve(params[0]));
396 | }
397 |
398 | @Override
399 | protected void onPostExecute(final Bitmap bm) {
400 | adView.animate()
401 | .alpha(0f)
402 | .setDuration(500)
403 | .setListener(new Animator.AnimatorListener() {
404 | @Override
405 | public void onAnimationStart(Animator animation) {
406 |
407 | }
408 |
409 | @Override
410 | public void onAnimationEnd(Animator animation) {
411 | adView.setImageBitmap(bm);
412 | adView.setAlpha(0f);
413 | adView.setVisibility(View.VISIBLE);
414 | adView.animate()
415 | .alpha(1f)
416 | .setDuration(1500)
417 | .setListener(null)
418 | .start();
419 | }
420 |
421 | @Override
422 | public void onAnimationCancel(Animator animation) {
423 |
424 | }
425 |
426 | @Override
427 | public void onAnimationRepeat(Animator animation) {
428 |
429 | }
430 | })
431 | .start();
432 |
433 | }
434 | }
435 | }
436 |
--------------------------------------------------------------------------------
/library/src/main/java/io/eisner/ads/GetResponse.java:
--------------------------------------------------------------------------------
1 | package io.eisner.ads;
2 |
3 | import android.os.AsyncTask;
4 |
5 | import com.squareup.okhttp.OkHttpClient;
6 | import com.squareup.okhttp.Request;
7 | import com.squareup.okhttp.Response;
8 | import com.squareup.okhttp.ResponseBody;
9 |
10 | import java.io.IOException;
11 | import java.io.InputStream;
12 | import java.util.concurrent.ExecutionException;
13 | import java.util.concurrent.TimeUnit;
14 |
15 | /**
16 | * AsyncTask to get a response from a server using a built request
17 | *
18 | * Created by nathan eisner on 10/13/15.
19 | */
20 | class GetResponse {
21 | private static OkHttpClient okClient = new OkHttpClient();
22 |
23 | static {
24 | okClient.setReadTimeout(30, TimeUnit.SECONDS);
25 | okClient.setConnectTimeout(30, TimeUnit.SECONDS);
26 | }
27 |
28 | /**
29 | * Get a http response for the bytes of the body
30 | *
31 | * @param request a built request
32 | * @return byte array of the contents of the body
33 | */
34 | public static byte[] forBytes(Request request) {
35 | try {
36 | Response response = okClient.newCall(request).execute();
37 | if (response != null && response.isSuccessful())
38 | return response.body().bytes();
39 | } catch (IOException e) {
40 | e.printStackTrace();
41 | }
42 | return new byte[0];
43 | }
44 |
45 | /**
46 | * Get a http response body
47 | *
48 | * @param request a build request
49 | * @return ResponseBody of the request sent
50 | */
51 | public static ResponseBody forBody(Request request) {
52 | try {
53 | Response response = okClient.newCall(request).execute();
54 | if (response != null && response.isSuccessful())
55 | return response.body();
56 | } catch (IOException e) {
57 | e.printStackTrace();
58 | }
59 | return null;
60 | }
61 |
62 | /**
63 | * Get a http response body in byte stream
64 | *
65 | * @param request a built request
66 | * @return the InputStream form of the body
67 | */
68 | public static InputStream forStream(Request request) {
69 | try {
70 | Response response = okClient.newCall(request).execute();
71 | if (response != null && response.isSuccessful())
72 | return response.body().byteStream();
73 | } catch (IOException e) {
74 | e.printStackTrace();
75 | }
76 | return null;
77 | }
78 |
79 | public static boolean forOK(Request request) {
80 | try {
81 | okClient.setConnectTimeout(10, TimeUnit.SECONDS);
82 | Response response = new GetOK().execute(request).get();
83 | okClient.setConnectTimeout(30, TimeUnit.SECONDS);
84 | return response != null && response.isSuccessful();
85 | } catch (InterruptedException | ExecutionException e) {
86 | e.printStackTrace();
87 | }
88 | return false;
89 | }
90 |
91 | private static class GetOK extends AsyncTask {
92 |
93 | @Override
94 | protected Response doInBackground(Request... params) {
95 | try {
96 | return okClient.newCall(params[0]).execute();
97 | } catch (IOException e) {
98 | e.printStackTrace();
99 | }
100 | return null;
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/library/src/main/java/io/eisner/ads/HeaderFields.java:
--------------------------------------------------------------------------------
1 | package io.eisner.ads;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import java.util.HashMap;
6 | import java.util.Set;
7 |
8 | /**
9 | * An easy way to store HTTP Header values for use when making requests
10 | * Created by nate eisner.
11 | */
12 | public class HeaderFields {
13 | protected HashMap headerMap;
14 |
15 | public HeaderFields() {
16 | headerMap = new HashMap<>();
17 | }
18 |
19 | public boolean add(@NonNull String name, @NonNull String value) {
20 | if (!headerMap.containsKey(name)) {
21 | headerMap.put(name, value);
22 | return true;
23 | } else
24 | return false;
25 | }
26 |
27 | public String[] getNameStrings() {
28 | return headerMap.keySet().toArray(new String[headerMap.size()]);
29 | }
30 |
31 | public Set getNameSet() {
32 | return headerMap.keySet();
33 | }
34 |
35 | public String getValue(@NonNull String name) {
36 | return headerMap.get(name);
37 | }
38 |
39 | public void update(@NonNull String name, @NonNull String value) {
40 | headerMap.put(name, value);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/library/src/main/res/drawable/placeholder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nate-eisner/android-ads/f751a5eda55a44104e9c66765f4e0089a9e56a19/library/src/main/res/drawable/placeholder.png
--------------------------------------------------------------------------------
/library/src/main/res/values/values.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | ads
4 |
5 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':example', ':library'
2 |
--------------------------------------------------------------------------------