diff --git a/.classpath b/.classpath
index 51769745..149cb3c9 100644
--- a/.classpath
+++ b/.classpath
@@ -1,9 +1,20 @@
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.gitignore b/.gitignore
index 0e69a217..7e78a6f9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,4 +28,5 @@ local.properties
.buildpath
*.DS_Store
bin/jarlist.cache
-test/test-reports/
\ No newline at end of file
+test/test-reports/
+/target/
diff --git a/.project b/.project
index f38a678f..30ba1f9b 100644
--- a/.project
+++ b/.project
@@ -1,33 +1,23 @@
- Connect-SDK-Android-Core
+ Connect-SDK-Java-Core
-
- com.android.ide.eclipse.adt.ResourceManagerBuilder
-
-
-
-
- com.android.ide.eclipse.adt.PreCompilerBuilder
-
-
- org.eclipse.jdt.core.javabuilder
- com.android.ide.eclipse.adt.ApkBuilder
+ org.eclipse.m2e.core.maven2Builder
- com.android.ide.eclipse.adt.AndroidNature
+ org.eclipse.m2e.core.maven2Natureorg.eclipse.jdt.core.javanature
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
deleted file mode 100644
index 0651a857..00000000
--- a/AndroidManifest.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
diff --git a/README.md b/README.md
index 2a64b7dd..fdff72db 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,7 @@
-#Connect SDK Core (Android)
+#Connect SDK Core
+
+This is a fork from the Android version of Connect SDK. In this version all dependencies to android are removed.
+
The Connect SDK Core contains all of the core classes required for basic operation of Connect SDK. The core also includes support for some select protocols which do not have any heavy and/or external dependencies. These protocols include:
- Apple TV
- DIAL
@@ -10,8 +13,7 @@ The Connect SDK Core contains all of the core classes required for basic operati
##General Information
For more information about Connect SDK, visit the [main repository](https://github.com/ConnectSDK/Connect-SDK-Android).
-##Setup
-Unless you are doing very specialized work to extend the SDK, you should not need to make direct use of this repository. Instead, clone the [main repository](https://github.com/ConnectSDK/Connect-SDK-Android), which includes this repository as a submodule.
+For details on this fork, visit the [project page](http://sprehn.github.io/Connect-SDK-Java-Core/).
##License
Copyright (c) 2013-2015 LG Electronics.
diff --git a/libs/java-websocket-patch.jar b/libs/java-websocket-patch.jar
deleted file mode 100644
index 22cda9f4..00000000
Binary files a/libs/java-websocket-patch.jar and /dev/null differ
diff --git a/libs/javax.jmdns_3.4.1-patch2.jar b/libs/javax.jmdns_3.4.1-patch2.jar
deleted file mode 100644
index be0fb34f..00000000
Binary files a/libs/javax.jmdns_3.4.1-patch2.jar and /dev/null differ
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 00000000..e60a4216
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,114 @@
+
+ 4.0.0
+ Connect-SDK-Java-Core
+ Connect-SDK-Java-Core
+ 1.1-SNAPSHOT
+
+
+ UTF-8
+
+
+
+
+ clojars.org
+ http://clojars.org/repo
+
+
+
+
+ src
+
+
+ maven-compiler-plugin
+ 3.5.1
+
+
+ 1.8
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.3
+
+ true
+
+
+
+
+ com.github.github
+ site-maven-plugin
+ 0.12
+
+
+
+ site
+
+ site-deploy
+
+ github
+ site built
+ ${site.path}
+ true
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.10.4
+
+
+ org.codehaus.mojo
+ findbugs-maven-plugin
+ 3.0.4
+
+ Max
+
+
+
+
+
+
+
+ org.json
+ json
+ 20140107
+
+
+ javax.jmdns
+ jmdns
+ 3.4.1
+
+
+ org.java-websocket
+ java-websocket
+ 1.3.1
+
+
+ org.apache.servicemix.bundles
+ org.apache.servicemix.bundles.xpp3
+ 1.1.4c_7
+
+
+ org.slf4j
+ slf4j-api
+ 1.7.21
+
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.2
+
+
+
+ https://github.com/sprehn/Connect-SDK-Java-Core
+ scm:git:https://github.com/sprehn/Connect-SDK-Java-Core.git
+
+
\ No newline at end of file
diff --git a/project.properties b/project.properties
deleted file mode 100644
index c24522b5..00000000
--- a/project.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-# This file is automatically generated by Android Tools.
-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
-#
-# This file must be checked in Version Control Systems.
-#
-# To customize properties used by the Ant build system edit
-# "ant.properties", and override values to adapt the script to your
-# project structure.
-#
-# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
-#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
-
-# Project target.
-target=android-22
-android.library=true
-android.library.reference.1=..
diff --git a/res/drawable-hdpi/ic_launcher.png b/res/drawable-hdpi/ic_launcher.png
deleted file mode 100644
index 96a442e5..00000000
Binary files a/res/drawable-hdpi/ic_launcher.png and /dev/null differ
diff --git a/res/drawable-mdpi/ic_launcher.png b/res/drawable-mdpi/ic_launcher.png
deleted file mode 100644
index 359047df..00000000
Binary files a/res/drawable-mdpi/ic_launcher.png and /dev/null differ
diff --git a/res/drawable-xhdpi/ic_launcher.png b/res/drawable-xhdpi/ic_launcher.png
deleted file mode 100644
index 71c6d760..00000000
Binary files a/res/drawable-xhdpi/ic_launcher.png and /dev/null differ
diff --git a/res/values-v11/styles.xml b/res/values-v11/styles.xml
deleted file mode 100644
index 3c02242a..00000000
--- a/res/values-v11/styles.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
diff --git a/res/values-v14/styles.xml b/res/values-v14/styles.xml
deleted file mode 100644
index a91fd037..00000000
--- a/res/values-v14/styles.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
diff --git a/res/values/strings.xml b/res/values/strings.xml
deleted file mode 100644
index 41274ae5..00000000
--- a/res/values/strings.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
- Connect-SDK-Android-Core
-
-
diff --git a/res/values/styles.xml b/res/values/styles.xml
deleted file mode 100644
index 6ce89c7b..00000000
--- a/res/values/styles.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/src/com/connectsdk/core/AppInfo.java b/src/com/connectsdk/core/AppInfo.java
index de157657..9d4543e8 100644
--- a/src/com/connectsdk/core/AppInfo.java
+++ b/src/com/connectsdk/core/AppInfo.java
@@ -57,6 +57,7 @@ public AppInfo(String id) {
* Gets the ID of the app on the first screen device. Format is different
* depending on the platform. (ex. youtube.leanback.v4, 0000001134, netflix,
* etc).
+ * @return ID of the app on the first screen device
*/
public String getId() {
return id;
@@ -66,6 +67,7 @@ public String getId() {
* Sets the ID of the app on the first screen device. Format is different
* depending on the platform. (ex. youtube.leanback.v4, 0000001134, netflix,
* etc).
+ * @param id ID of the app on the first screen device
*/
public void setId(String id) {
this.id = id;
@@ -74,6 +76,7 @@ public void setId(String id) {
/**
* Gets the user-friendly name of the app (ex. YouTube, Browser, Netflix,
* etc).
+ * @return user-friendly name of the app
*/
public String getName() {
return name;
@@ -82,17 +85,18 @@ public String getName() {
/**
* Sets the user-friendly name of the app (ex. YouTube, Browser, Netflix,
* etc).
+ * @param name user-friendly name of the app
*/
public void setName(String name) {
this.name = name.trim();
}
- /** Gets the raw data from the first screen device about the app. */
+ /** @return the raw data from the first screen device about the app. */
public JSONObject getRawData() {
return raw;
}
- /** Sets the raw data from the first screen device about the app. */
+ /** @param data the raw data from the first screen device about the app. */
public void setRawData(JSONObject data) {
raw = data;
}
@@ -110,20 +114,29 @@ public JSONObject toJSONObject() throws JSONException {
// @endcond
- /**
- * Compares two AppInfo objects.
- *
- * @param o
- * Other AppInfo object to compare.
- *
- * @return true if both AppInfo id values are equal
- */
@Override
- public boolean equals(Object o) {
- if (o instanceof AppInfo) {
- AppInfo ai = (AppInfo) o;
- return this.id.equals(ai.id);
- }
- return super.equals(o);
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
}
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ AppInfo other = (AppInfo) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ return true;
+ }
+
}
diff --git a/src/com/connectsdk/core/ChannelInfo.java b/src/com/connectsdk/core/ChannelInfo.java
index 0211b580..4145fc3f 100644
--- a/src/com/connectsdk/core/ChannelInfo.java
+++ b/src/com/connectsdk/core/ChannelInfo.java
@@ -23,8 +23,6 @@
import org.json.JSONException;
import org.json.JSONObject;
-import android.util.Log;
-
/**
* Normalized reference object for information about a TVs channels. This object is required to set the channel on a TV.
*/
@@ -45,98 +43,69 @@ public class ChannelInfo implements JSONSerializable {
public ChannelInfo() {
}
- /** Gets the raw data from the first screen device about the channel. In most cases, this is an NSDictionary. */
+ /** @return the raw data from the first screen device about the channel. In most cases, this is an NSDictionary. */
public JSONObject getRawData() {
return rawData;
}
- /** Sets the raw data from the first screen device about the channel. In most cases, this is an NSDictionary. */
+ /**
+ * @param rawData the raw data from the first screen device about the channel. In most cases, this is an
+ * NSDictionary.
+ */
public void setRawData(JSONObject rawData) {
this.rawData = rawData;
}
- /** Gets the user-friendly name of the channel */
+ /** @return the user-friendly name of the channel */
public String getName() {
return channelName;
}
- /** Sets the user-friendly name of the channel */
+ /** @param channelName the user-friendly name of the channel */
public void setName(String channelName) {
this.channelName = channelName;
}
- /** Gets the TV's unique ID for the channel */
+ /** @return the TV's unique ID for the channel */
public String getId() {
return channelId;
}
- /** Sets the TV's unique ID for the channel */
+ /** @param channelId the TV's unique ID for the channel */
public void setId(String channelId) {
this.channelId = channelId;
}
- /** Gets the TV channel's number (likely to be a combination of the major & minor numbers) */
+ /** @return the TV channel's number (likely to be a combination of the major & minor numbers) */
public String getNumber() {
return channelNumber;
}
- /** Sets the TV channel's number (likely to be a combination of the major & minor numbers) */
+ /** @param channelNumber the TV channel's number (likely to be a combination of the major & minor numbers) */
public void setNumber(String channelNumber) {
this.channelNumber = channelNumber;
}
- /** Gets the TV channel's minor number */
+ /** @return the TV channel's minor number */
public int getMinorNumber() {
return minorNumber;
}
- /** Sets the TV channel's minor number */
+ /** @param minorNumber the TV channel's minor number */
public void setMinorNumber(int minorNumber) {
this.minorNumber = minorNumber;
}
- /** Gets the TV channel's major number */
+ /** @return the TV channel's major number */
public int getMajorNumber() {
return majorNumber;
}
- /** Sets the TV channel's major number */
+ /** @param majorNumber the TV channel's major number */
public void setMajorNumber(int majorNumber) {
this.majorNumber = majorNumber;
}
- /**
- * Compares two ChannelInfo objects.
- *
- * @param channelInfo ChannelInfo object to compare.
- *
- * @return YES if both ChannelInfo number & name values are equal
- */
- @Override
- public boolean equals(Object o) {
- if (o instanceof ChannelInfo) {
- ChannelInfo other = (ChannelInfo) o;
-
- if (this.channelId != null) {
- if (this.channelId.equals(other.channelId))
- return true;
- } else if (this.channelName != null && this.channelNumber != null) {
- return this.channelName.equals(other.channelName)
- && this.channelNumber.equals(other.channelNumber)
- && this.majorNumber == other.majorNumber
- && this.minorNumber == other.minorNumber;
- }
-
- Log.d(Util.T, "Could not compare channel values, no data to compare against");
- Log.d(Util.T, "This channel info: \n" + this.rawData.toString());
- Log.d(Util.T, "Other channel info: \n" + other.rawData.toString());
-
- return false;
- }
-
- return super.equals(o);
- }
-
// @cond INTERNAL
@Override
public JSONObject toJSONObject() throws JSONException {
@@ -152,4 +121,51 @@ public JSONObject toJSONObject() throws JSONException {
return obj;
}
// @endcond
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ if (channelId != null) {
+ result = prime * result + channelId.hashCode();
+ } else {
+ result = prime * result + ((channelName == null) ? 0 : channelName.hashCode());
+ result = prime * result + ((channelNumber == null) ? 0 : channelNumber.hashCode());
+ result = prime * result + majorNumber;
+ result = prime * result + minorNumber;
+ }
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ChannelInfo other = (ChannelInfo) obj;
+
+ if (channelId != null) {
+ if (channelId.equals(other.channelId))
+ return true;
+ }
+
+ if (channelName == null) {
+ if (other.channelName != null)
+ return false;
+ } else if (!channelName.equals(other.channelName))
+ return false;
+ if (channelNumber == null) {
+ if (other.channelNumber != null)
+ return false;
+ } else if (!channelNumber.equals(other.channelNumber))
+ return false;
+ if (majorNumber != other.majorNumber)
+ return false;
+ if (minorNumber != other.minorNumber)
+ return false;
+ return true;
+ }
}
diff --git a/src/com/connectsdk/core/Context.java b/src/com/connectsdk/core/Context.java
new file mode 100644
index 00000000..d8362304
--- /dev/null
+++ b/src/com/connectsdk/core/Context.java
@@ -0,0 +1,11 @@
+package com.connectsdk.core;
+
+import java.net.InetAddress;
+
+/** Interface that must be implemented for the library to interface with surrounding environment. */
+public interface Context {
+ public String getPackageName();
+ public String getDataDir();
+ public String getApplicationName();
+ public InetAddress getIpAddress();
+}
diff --git a/src/com/connectsdk/core/ExternalInputInfo.java b/src/com/connectsdk/core/ExternalInputInfo.java
index f093a5ef..8db1599b 100644
--- a/src/com/connectsdk/core/ExternalInputInfo.java
+++ b/src/com/connectsdk/core/ExternalInputInfo.java
@@ -40,52 +40,52 @@ public class ExternalInputInfo implements JSONSerializable {
public ExternalInputInfo() {
}
- /** Gets the ID of the external input on the first screen device. */
+ /** @return the ID of the external input on the first screen device. */
public String getId() {
return id;
}
- /** Sets the ID of the external input on the first screen device. */
+ /** @param inputId the ID of the external input on the first screen device. */
public void setId(String inputId) {
this.id = inputId;
}
- /** Gets the user-friendly name of the external input (ex. AV, HDMI1, etc). */
+ /** @return the user-friendly name of the external input (ex. AV, HDMI1, etc). */
public String getName() {
return name;
}
- /** Sets the user-friendly name of the external input (ex. AV, HDMI1, etc). */
+ /** @param inputName the user-friendly name of the external input (ex. AV, HDMI1, etc). */
public void setName(String inputName) {
this.name = inputName;
}
- /** Sets the raw data from the first screen device about the external input. */
+ /** @param rawData the raw data from the first screen device about the external input. */
public void setRawData(JSONObject rawData) {
this.rawData = rawData;
}
- /** Gets the raw data from the first screen device about the external input. */
+ /** @return the raw data from the first screen device about the external input. */
public JSONObject getRawData() {
return rawData;
}
- /** Whether the DeviceService is currently connected to this external input. */
+ /** @return true if the DeviceService is currently connected to this external input. */
public boolean isConnected() {
return connected;
}
- /** Sets whether the DeviceService is currently connected to this external input. */
+ /** @param connected whether the DeviceService is currently connected to this external input. */
public void setConnected(boolean connected) {
this.connected = connected;
}
- /** Gets the URL to an icon representing this external input. */
+ /** @return the URL to an icon representing this external input. */
public String getIconURL() {
return iconURL;
}
- /** Sets the URL to an icon representing this external input. */
+ /** @param iconURL the URL to an icon representing this external input. */
public void setIconURL(String iconURL) {
this.iconURL = iconURL;
}
@@ -105,20 +105,36 @@ public JSONObject toJSONObject() throws JSONException {
}
// @endcond
- /**
- * Compares two ExternalInputInfo objects.
- *
- * @param externalInputInfo ExternalInputInfo object to compare.
- *
- * @return YES if both ExternalInputInfo id & name values are equal
- */
@Override
- public boolean equals(Object o) {
- if (o instanceof ExternalInputInfo) {
- ExternalInputInfo eii = (ExternalInputInfo) o;
- return this.id.equals(eii.id) &&
- this.name.equals(eii.name);
- }
- return false;
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ExternalInputInfo other = (ExternalInputInfo) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
}
+
+
}
diff --git a/src/com/connectsdk/core/ImageInfo.java b/src/com/connectsdk/core/ImageInfo.java
index 88fdd95e..d4d9a7db 100644
--- a/src/com/connectsdk/core/ImageInfo.java
+++ b/src/com/connectsdk/core/ImageInfo.java
@@ -29,7 +29,7 @@ public class ImageInfo {
/**
* Default constructor method.
- * @param url
+ * @param url the url
*/
public ImageInfo(String url) {
@@ -37,12 +37,6 @@ public ImageInfo(String url) {
this.url = url;
}
- /**
- * Default constructor method.
- * @param url, type, width, height
- * add type of file, width and height of image.
- */
-
public ImageInfo(String url, ImageType type, int width, int height) {
this(url);
this.type = type;
@@ -50,7 +44,6 @@ public ImageInfo(String url, ImageType type, int width, int height) {
this.height = height;
}
-
public enum ImageType {
Thumb, Video_Poster, Album_Art, Unknown
}
@@ -60,75 +53,36 @@ public enum ImageType {
private int width;
private int height;
- /**
- * Gets URL address of an image file.
- *
- */
-
public String getUrl() {
return url;
}
-
- /**
- * Sets URL address of an image file.
- *
- */
-
public void setUrl(String url) {
this.url = url;
- }
-
- /**
- * Gets a type of an image file.
- *
- */
+ }
public ImageType getType() {
return type;
}
- /**
- * Sets a type of an image file.
- *
- */
-
+
public void setType(ImageType type) {
this.type = type;
}
- /**
- * Gets a width of an image.
- *
- */
-
+
public int getWidth() {
return width;
}
- /**
- * Sets a width of an image.
- *
- */
-
public void setWidth(int width) {
this.width = width;
}
- /**
- * Gets a height of an image.
- *
- */
-
public int getHeight() {
return height;
}
- /**
- * Sets a height of an image.
- *
- */
-
public void setHeight(int height) {
this.height = height;
}
diff --git a/src/com/connectsdk/core/Log.java b/src/com/connectsdk/core/Log.java
new file mode 100644
index 00000000..3ae22e0e
--- /dev/null
+++ b/src/com/connectsdk/core/Log.java
@@ -0,0 +1,31 @@
+package com.connectsdk.core;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class Log {
+
+ private static final Logger l = LoggerFactory.getLogger(Log.class);
+
+ public static int d(java.lang.String tag, java.lang.String msg) {
+ l.debug(String.format("%s - %s", tag, msg));
+ return 0;
+ }
+
+ public static int w(java.lang.String tag, java.lang.String msg) {
+ l.warn(String.format("%s - %s", tag, msg));
+ return 0;
+ }
+
+ public static int e(java.lang.String tag, java.lang.String msg) {
+ l.error(String.format("%s - %s",tag, msg));
+ return 0;
+ }
+
+ public static int e(java.lang.String tag, java.lang.String msg, java.lang.Throwable tr) {
+ l.error(String.format("%s - %s",tag, msg), tr);
+ return 0;
+ }
+
+
+}
diff --git a/src/com/connectsdk/core/MediaInfo.java b/src/com/connectsdk/core/MediaInfo.java
index b05c2cbf..32796de8 100644
--- a/src/com/connectsdk/core/MediaInfo.java
+++ b/src/com/connectsdk/core/MediaInfo.java
@@ -20,8 +20,6 @@
package com.connectsdk.core;
-import android.support.annotation.NonNull;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -154,58 +152,35 @@ public MediaInfo(String url, String mimeType, String title, String description,
this.allImages = allImages;
}
- /**
- * Gets type of a media file.
- */
public String getMimeType() {
return mimeType;
}
- /**
- * Sets type of a media file.
- *
- * This method is deprecated
- */
@Deprecated
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
- /**
- * Gets title for a media file.
- */
public String getTitle() {
return title;
}
- /**
- * Sets title of a media file.
- *
- * This method is deprecated
- */
@Deprecated
public void setTitle(String title) {
this.title = title;
}
- /**
- * Gets description for a media.
- */
public String getDescription() {
return description;
}
- /**
- * Sets description for a media.
- * This method is deprecated
- */
@Deprecated
public void setDescription(String description) {
this.description = description;
}
/**
- * Gets list of ImageInfo objects for images representing a media (ex. icon, poster).
+ * @return list of ImageInfo objects for images representing a media (ex. icon, poster).
* Where first ([0]) is icon image, and second ([1]) is poster image.
*/
public List getImages() {
@@ -216,40 +191,26 @@ public List getImages() {
* Sets list of ImageInfo objects for images representing a media (ex. icon, poster).
* Where first ([0]) is icon image, and second ([1]) is poster image.
*
- * This method is deprecated
+ * @param images the pair of images
*/
@Deprecated
public void setImages(List images) {
this.allImages = images;
}
- /**
- * Gets duration of a media file.
- */
public long getDuration() {
return duration;
}
- /**
- * Sets duration of a media file.
- * This method is deprecated
- */
@Deprecated
public void setDuration(long duration) {
this.duration = duration;
}
- /**
- * Gets URL address of a media file.
- */
public String getUrl() {
return url;
}
- /**
- * Sets URL address of a media file.
- * This method is deprecated
- */
@Deprecated
public void setUrl(String url) {
this.url = url;
@@ -259,11 +220,6 @@ public SubtitleInfo getSubtitleInfo() {
return subtitleInfo;
}
- /**
- * Stores ImageInfo objects.
- *
- * This method is deprecated
- */
@Deprecated
public void addImages(ImageInfo... images) {
if (images == null) {
diff --git a/src/com/connectsdk/core/NonNull.java b/src/com/connectsdk/core/NonNull.java
new file mode 100644
index 00000000..7658b124
--- /dev/null
+++ b/src/com/connectsdk/core/NonNull.java
@@ -0,0 +1,16 @@
+package com.connectsdk.core;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.RetentionPolicy.CLASS;
+/**
+ * Denotes that a parameter, field or method return value can never be null.
+ *
+ * This is a marker annotation and it has no specific attributes.
+ */
+@Retention(CLASS)
+@Target({METHOD, PARAMETER, FIELD})
+public @interface NonNull {
+}
\ No newline at end of file
diff --git a/src/com/connectsdk/core/PointF.java b/src/com/connectsdk/core/PointF.java
new file mode 100644
index 00000000..8112afc6
--- /dev/null
+++ b/src/com/connectsdk/core/PointF.java
@@ -0,0 +1,11 @@
+package com.connectsdk.core;
+
+public class PointF {
+ public PointF(float x, float y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public float x;
+ public float y;
+}
diff --git a/src/com/connectsdk/core/ProgramInfo.java b/src/com/connectsdk/core/ProgramInfo.java
index 57e42312..31f778bf 100644
--- a/src/com/connectsdk/core/ProgramInfo.java
+++ b/src/com/connectsdk/core/ProgramInfo.java
@@ -31,60 +31,76 @@ public class ProgramInfo {
private Object rawData;
// @endcond
- /** Gets the ID of the program on the first screen device. Format is different depending on the platform. */
+ /** Returns the ID of the program on the first screen device. Format is different depending on the platform.
+ * @return the ID */
public String getId() {
return id;
}
- /** Sets the ID of the program on the first screen device. Format is different depending on the platform. */
+ /** Sets the ID of the program on the first screen device. Format is different depending on the platform.
+ * @param id the ID */
public void setId(String id) {
this.id = id;
}
- /** Gets the user-friendly name of the program (ex. Sesame Street, Cosmos, Game of Thrones, etc). */
+ /** @return the user-friendly name of the program (ex. Sesame Street, Cosmos, Game of Thrones, etc). */
public String getName() {
return name;
}
- /** Sets the user-friendly name of the program (ex. Sesame Street, Cosmos, Game of Thrones, etc). */
+ /** Sets the user-friendly name of the program (ex. Sesame Street, Cosmos, Game of Thrones, etc).
+ * @param name the name */
public void setName(String name) {
this.name = name;
}
- /** Gets the reference to the ChannelInfo object that this program is associated with */
public ChannelInfo getChannelInfo() {
return channelInfo;
}
- /** Sets the reference to the ChannelInfo object that this program is associated with */
public void setChannelInfo(ChannelInfo channelInfo) {
this.channelInfo = channelInfo;
}
- /** Gets the raw data from the first screen device about the program. In most cases, this is an NSDictionary. */
+ /** @return the raw data from the first screen device about the program. In most cases, this is an NSDictionary. */
public Object getRawData() {
return rawData;
}
- /** Sets the raw data from the first screen device about the program. In most cases, this is an NSDictionary. */
public void setRawData(Object rawData) {
this.rawData = rawData;
}
- /**
- * Compares two ProgramInfo objects.
- *
- * @param programInfo ProgramInfo object to compare.
- *
- * @return true if both ProgramInfo id & name values are equal
- */
@Override
- public boolean equals(Object o) {
- if (o instanceof ProgramInfo) {
- ProgramInfo pi = (ProgramInfo) o;
- return pi.id.equals(pi.id) &&
- pi.name.equals(pi.name);
- }
- return super.equals(o);
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
}
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ProgramInfo other = (ProgramInfo) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+
}
diff --git a/src/com/connectsdk/core/SubtitleInfo.java b/src/com/connectsdk/core/SubtitleInfo.java
index d14bfa7f..3ea33818 100644
--- a/src/com/connectsdk/core/SubtitleInfo.java
+++ b/src/com/connectsdk/core/SubtitleInfo.java
@@ -19,22 +19,22 @@
*/
package com.connectsdk.core;
-import android.support.annotation.NonNull;
-
/**
* Normalized reference object for information about a subtitle track. It's used in `MediaInfo` class.
* The only one required parameter is `url`, others can be `null`. This class is immutable and has
* a builder for easy construction.
*
* Different services support specific subtitle formats:
- * - `DLNAService` supports only SRT subtitles. Since there is no official specification for them,
- * subtitles may not work on all DLNA-compatible devices
- * - `NetcastTVService` supports only SRT subtitles and has the same restrictions as `DLNAService`
- * - `CastService` supports only WebVTT subtitles and it has additional requirements
- * @see {@link https://developers.google.com/cast/docs/android_sender#cors-requirements}
- * - `FireTVService` supports only WebVTT subtitles
- * - `WebOSTVService` supports WebVTT subtitles. Server providing subtitles should
- * support CORS headers, similarly to Cast service's requirements.
+ *
+ *
`DLNAService` supports only SRT subtitles. Since there is no official specification for them,
+ * subtitles may not work on all DLNA-compatible devices
+ *
`NetcastTVService` supports only SRT subtitles and has the same restrictions as `DLNAService`
+ *
`CastService` supports only WebVTT subtitles and it has additional
+ * requirements
+ *
`FireTVService` supports only WebVTT subtitles
+ *
`WebOSTVService` supports WebVTT subtitles. Server providing subtitles should
+ * support CORS headers, similarly to Cast service's requirements.
+ *
*
*/
public class SubtitleInfo {
diff --git a/src/com/connectsdk/core/TextInputStatusInfo.java b/src/com/connectsdk/core/TextInputStatusInfo.java
index b31237a2..e43587d7 100644
--- a/src/com/connectsdk/core/TextInputStatusInfo.java
+++ b/src/com/connectsdk/core/TextInputStatusInfo.java
@@ -55,7 +55,8 @@ public void setFocused(boolean focused) {
this.focused = focused;
}
- /** Gets the type of keyboard that should be displayed to the user. */
+ /** Gets the type of keyboard that should be displayed to the user.
+ * @return the keyboard type */
public TextInputType getTextInputType() {
TextInputType textInputType = TextInputType.DEFAULT;
@@ -77,7 +78,8 @@ else if (contentType.equals("email")) {
return textInputType;
}
- /** Sets the type of keyboard that should be displayed to the user. */
+ /** Sets the type of keyboard that should be displayed to the user.
+ * @param textInputType the keyboard type*/
public void setTextInputType(TextInputType textInputType) {
switch (textInputType) {
case NUMBER:
@@ -135,12 +137,12 @@ public void setHiddenText(boolean hiddenText) {
this.hiddenText = hiddenText;
}
- /** Gets the raw data from the first screen device about the text input status. */
+ /** @return the raw data from the first screen device about the text input status. */
public JSONObject getRawData() {
return rawData;
}
- /** Sets the raw data from the first screen device about the text input status. */
+ /** @param data the raw data from the first screen device about the text input status. */
public void setRawData(JSONObject data) {
rawData = data;
}
diff --git a/src/com/connectsdk/core/Util.java b/src/com/connectsdk/core/Util.java
index 75378138..d43a0497 100644
--- a/src/com/connectsdk/core/Util.java
+++ b/src/com/connectsdk/core/Util.java
@@ -20,78 +20,52 @@
package com.connectsdk.core;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
+
+
import java.util.Date;
-import java.util.concurrent.Executor;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
-import android.content.Context;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.os.Handler;
-import android.os.Looper;
-
import com.connectsdk.service.capability.listeners.ErrorListener;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.ServiceCommandError;
-public final class Util {
- static public String T = "Connect SDK";
- static private Handler handler;
- static private final int NUM_OF_THREADS = 20;
+public final class Util {
+ static public final String T = "Connect SDK";
- static private Executor executor;
+ static private ExecutorService executor;
- static {
- createExecutor();
+ /**
+ * Configure Util on component start.
+ *
+ * @param e must not be null
+ */
+ public static void init(ExecutorService e) {
+ executor = e;
}
- static void createExecutor() {
- Util.executor = Executors.newFixedThreadPool(NUM_OF_THREADS, new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- Thread th = new Thread(r);
- th.setName("2nd Screen BG");
- return th;
- }
- });
+ public static void uninit() {
+ executor = null;
}
public static void runOnUI(Runnable runnable) {
- if (handler == null) {
- handler = new Handler(Looper.getMainLooper());
- }
-
- handler.post(runnable);
+ // no UI in openhab
+ runInBackground(runnable, true);
}
public static void runInBackground(Runnable runnable, boolean forceNewThread) {
- if (forceNewThread || isMain()) {
- executor.execute(runnable);
- } else {
- runnable.run();
- }
-
+ executor.execute(runnable);
}
public static void runInBackground(Runnable runnable) {
runInBackground(runnable, false);
}
- public static Executor getExecutor() {
- return executor;
- }
-
- public static boolean isMain() {
- return Looper.myLooper() == Looper.getMainLooper();
- }
+
public static void postSuccess(final ResponseListener listener, final T object) {
if (listener == null)
@@ -117,15 +91,7 @@ public void run() {
listener.onError(error);
}
});
- }
-
- public static byte[] convertIpAddress(int ip) {
- return new byte[] {
- (byte) (ip & 0xFF),
- (byte) ((ip >> 8) & 0xFF),
- (byte) ((ip >> 16) & 0xFF),
- (byte) ((ip >> 24) & 0xFF)};
- }
+ }
public static long getTime() {
return TimeUnit.MILLISECONDS.toSeconds(new Date().getTime());
@@ -135,21 +101,5 @@ public static boolean isIPv4Address(String ipAddress) {
return InetAddressUtils.isIPv4Address(ipAddress);
}
- public static boolean isIPv6Address(String ipAddress) {
- return InetAddressUtils.isIPv6Address(ipAddress);
- }
-
- public static InetAddress getIpAddress(Context context) throws UnknownHostException {
- WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
- WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
- int ip = wifiInfo.getIpAddress();
-
- if (ip == 0) {
- return null;
- }
- else {
- byte[] ipAddress = convertIpAddress(ip);
- return InetAddress.getByAddress(ipAddress);
- }
- }
+
}
\ No newline at end of file
diff --git a/src/com/connectsdk/device/ConnectableDevice.java b/src/com/connectsdk/device/ConnectableDevice.java
index d63230e5..a12e8fa4 100644
--- a/src/com/connectsdk/device/ConnectableDevice.java
+++ b/src/com/connectsdk/device/ConnectableDevice.java
@@ -31,8 +31,7 @@
import org.json.JSONException;
import org.json.JSONObject;
-import android.util.Log;
-
+import com.connectsdk.core.Log;
import com.connectsdk.core.Util;
import com.connectsdk.discovery.DiscoveryManager;
import com.connectsdk.service.DeviceService;
@@ -97,7 +96,7 @@ public class ConnectableDevice implements DeviceServiceListener {
Map services;
- public boolean featuresReady = false;
+ //public boolean featuresReady = false;
public ConnectableDevice() {
services = new ConcurrentHashMap();
@@ -152,8 +151,8 @@ public void setServiceDescription(ServiceDescription serviceDescription) {
// @endcond
/**
- * set desirable pairing type for all services
- * @param pairingType
+ * Set desirable pairing type for all services.
+ * @param pairingType the pairing type
*/
public void setPairingType(PairingType pairingType) {
Collection services = getServices();
@@ -232,7 +231,7 @@ private synchronized List getMismatchCapabilities(List capabilit
return list;
}
- /** Array of all currently discovered DeviceServices this ConnectableDevice has associated with it. */
+ /** @return Collection of all currently discovered DeviceServices this ConnectableDevice has associated with it. */
public Collection getServices() {
return services.values();
}
@@ -263,9 +262,10 @@ public void removeServiceByName(String serviceName) {
}
/**
- * Returns a DeviceService from the ConnectableDevice instance. serviceUUID is used as the identifier because only one instance of each DeviceService type may be attached to a single ConnectableDevice instance.
+ * Get DeviceService from the ConnectableDevice instance. serviceUUID is used as the identifier because only one instance of each DeviceService type may be attached to a single ConnectableDevice instance.
*
* @param serviceUUID UUID of the DeviceService to be returned
+ * @return DeviceService from the ConnectableDevice instance
*/
public DeviceService getServiceWithUUID(String serviceUUID) {
for (DeviceService service : getServices()) {
@@ -370,7 +370,7 @@ public boolean isConnected() {
// @endcond
/**
- * Whether the device has any DeviceServices that require an active connection (websocket, HTTP registration, etc)
+ * @return true, if the device has any DeviceServices that require an active connection (websocket, HTTP registration, etc)
*/
public boolean isConnectable() {
for (DeviceService service: services.values()) {
@@ -399,7 +399,7 @@ public void cancelPairing() {
}
}
- /** A combined list of all capabilities that are supported among the detected DeviceServices. */
+ /** @return A combined list of all capabilities that are supported among the detected DeviceServices. */
public synchronized List getCapabilities() {
List caps = new ArrayList();
@@ -422,6 +422,7 @@ public synchronized List getCapabilities() {
* Example: `Launcher.App.Any`
*
* @param capability Capability to test against
+ * @return true if the capbaility exists
*/
public boolean hasCapability(String capability) {
boolean hasCap = false;
@@ -442,6 +443,7 @@ public boolean hasCapability(String capability) {
* See hasCapability: for a description of the wildcard feature provided by this method.
*
* @param capabilities Array of capabilities to test against
+ * @return true if at least one capability exists
*/
public boolean hasAnyCapability(String... capabilities) {
for (DeviceService service : services.values()) {
@@ -458,6 +460,7 @@ public boolean hasAnyCapability(String... capabilities) {
* See hasCapability: for a description of the wildcard feature provided by this method.
*
* @param capabilities Array of capabilities to test against
+ * @return true if the device has all those capabilities
*/
public synchronized boolean hasCapabilities(List capabilities) {
String[] arr = new String[capabilities.size()];
@@ -471,6 +474,7 @@ public synchronized boolean hasCapabilities(List capabilities) {
* See hasCapability: for a description of the wildcard feature provided by this method.
*
* @param capabilites Array of capabilities to test against
+ * @return true if the device has all those capabilities
*/
public synchronized boolean hasCapabilities(String... capabilites) {
boolean hasCaps = true;
@@ -485,140 +489,12 @@ public synchronized boolean hasCapabilities(String... capabilites) {
return hasCaps;
}
- /**
- * Accessor for highest priority Launcher object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public Launcher getLauncher() {
- return getCapability(Launcher.class);
- }
-
- /**
- * Accessor for highest priority MediaPlayer object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public MediaPlayer getMediaPlayer() {
- return getCapability(MediaPlayer.class);
- }
-
- /**
- * Accessor for highest priority MediaControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public MediaControl getMediaControl() {
- return getCapability(MediaControl.class);
- }
-
- /**
- * Accessor for highest priority PlaylistControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public PlaylistControl getPlaylistControl() {
- return getCapability(PlaylistControl.class);
- }
-
- /**
- * Accessor for highest priority VolumeControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public VolumeControl getVolumeControl() {
- return getCapability(VolumeControl.class);
- }
-
- /**
- * Accessor for highest priority WebAppLauncher object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public WebAppLauncher getWebAppLauncher() {
- return getCapability(WebAppLauncher.class);
- }
-
- /**
- * Accessor for highest priority TVControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public TVControl getTVControl() {
- return getCapability(TVControl.class);
- }
-
- /**
- * Accessor for highest priority ToastControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public ToastControl getToastControl() {
- return getCapability(ToastControl.class);
- }
-
- /**
- * Accessor for highest priority TextInputControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public TextInputControl getTextInputControl() {
- return getCapability(TextInputControl.class);
- }
-
- /**
- * Accessor for highest priority MouseControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public MouseControl getMouseControl() {
- return getCapability(MouseControl.class);
- }
-
- /**
- * Accessor for highest priority ExternalInputControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public ExternalInputControl getExternalInputControl() {
- return getCapability(ExternalInputControl.class);
- }
-
- /**
- * Accessor for highest priority PowerLauncher object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public PowerControl getPowerControl() {
- return getCapability(PowerControl.class);
- }
-
- /**
- * Accessor for highest priority KeyControl object
- * This method is deprecated. Use
- * `ConnectableDevice#getCapability(Class controllerClass)` method instead
- */
- @Deprecated
- public KeyControl getKeyControl() {
- return getCapability(KeyControl.class);
- }
/**
* Get a capability with the highest priority from a device. If device doesn't have such
* capability then returns null.
* @param controllerClass type of capability
+ * @param a capability methods class
* @return capability implementation
*/
public T getCapability(Class controllerClass) {
@@ -659,7 +535,7 @@ public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
- /** Gets the Current IP address of the ConnectableDevice. */
+ /** @return the Current IP address of the ConnectableDevice. */
public String getIpAddress() {
return ipAddress;
}
@@ -673,7 +549,7 @@ public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
- /** Gets an estimate of the ConnectableDevice's current friendly name. */
+ /** @return an estimate of the ConnectableDevice's current friendly name. */
public String getFriendlyName() {
return friendlyName;
}
@@ -681,13 +557,13 @@ public String getFriendlyName() {
/**
* Sets the last IP address this ConnectableDevice was discovered at.
*
- * @param lastKnownIPAddress Last known IP address of the device & it's services
+ * @param lastKnownIPAddress Last known IP address of the device & it's services
*/
public void setLastKnownIPAddress(String lastKnownIPAddress) {
this.lastKnownIPAddress = lastKnownIPAddress;
}
- /** Gets the last IP address this ConnectableDevice was discovered at. */
+ /** @return the last IP address this ConnectableDevice was discovered at. */
public String getLastKnownIPAddress() {
return lastKnownIPAddress;
}
@@ -695,13 +571,13 @@ public String getLastKnownIPAddress() {
/**
* Sets the name of the last wireless network this ConnectableDevice was discovered on.
*
- * @param lastSeenOnWifi Last Wi-Fi network this device & it's services were discovered on
+ * @param lastSeenOnWifi Last Wi-Fi network this device & it's services were discovered on
*/
public void setLastSeenOnWifi(String lastSeenOnWifi) {
this.lastSeenOnWifi = lastSeenOnWifi;
}
- /** Gets the name of the last wireless network this ConnectableDevice was discovered on. */
+ /** @return the name of the last wireless network this ConnectableDevice was discovered on. */
public String getLastSeenOnWifi() {
return lastSeenOnWifi;
}
@@ -715,7 +591,7 @@ public void setLastConnected(long lastConnected) {
this.lastConnected = lastConnected;
}
- /** Gets the last time (in milli seconds from 1970) that this ConnectableDevice was connected to. */
+ /** @return the last time (in milli seconds from 1970) that this ConnectableDevice was connected to. */
public long getLastConnected() {
return lastConnected;
}
@@ -729,7 +605,7 @@ public void setLastDetection(long lastDetection) {
this.lastDetection = lastDetection;
}
- /** Gets the last time (in milli seconds from 1970) that this ConnectableDevice was detected. */
+ /** @return the last time (in milli seconds from 1970) that this ConnectableDevice was detected. */
public long getLastDetection() {
return lastDetection;
}
@@ -743,7 +619,7 @@ public void setModelName(String modelName) {
this.modelName = modelName;
}
- /** Gets an estimate of the ConnectableDevice's current model name. */
+ /** @return an estimate of the ConnectableDevice's current model name. */
public String getModelName() {
return modelName;
}
@@ -757,7 +633,7 @@ public void setModelNumber(String modelNumber) {
this.modelNumber = modelNumber;
}
- /** Gets an estimate of the ConnectableDevice's current model number. */
+ /** @return an estimate of the ConnectableDevice's current model number. */
public String getModelNumber() {
return modelNumber;
}
@@ -771,7 +647,7 @@ public void setId(String id) {
}
/**
- * Universally unique id of this particular ConnectableDevice object, persists between sessions in ConnectableDeviceStore for connected devices
+ * @return universally unique id of this particular ConnectableDevice object, persists between sessions in ConnectableDeviceStore for connected devices
*/
public String getId() {
if (this.id == null)
diff --git a/src/com/connectsdk/device/ConnectableDeviceListener.java b/src/com/connectsdk/device/ConnectableDeviceListener.java
index ff1fbbaa..ef00a7e5 100644
--- a/src/com/connectsdk/device/ConnectableDeviceListener.java
+++ b/src/com/connectsdk/device/ConnectableDeviceListener.java
@@ -61,13 +61,13 @@ public interface ConnectableDeviceListener {
public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType);
/**
- * When a ConnectableDevice finds & loses DeviceServices, that ConnectableDevice will experience a change in its collective capabilities list. When such a change occurs, this message will be sent with arrays of capabilities that were added & removed.
+ * When a ConnectableDevice finds & loses DeviceServices, that ConnectableDevice will experience a change in its collective capabilities list. When such a change occurs, this message will be sent with arrays of capabilities that were added & removed.
*
* This message will allow you to decide when to stop/start interacting with a ConnectableDevice, based off of its supported capabilities.
*
* @param device ConnectableDevice that has experienced a change in capabilities
- * @param added List of capabilities that are new to the ConnectableDevice
- * @param removed List of capabilities that the ConnectableDevice has lost
+ * @param added capabilities that are new to the ConnectableDevice
+ * @param removed capabilities that the ConnectableDevice has lost
*/
public void onCapabilityUpdated(ConnectableDevice device, List added, List removed);
diff --git a/src/com/connectsdk/device/ConnectableDeviceStore.java b/src/com/connectsdk/device/ConnectableDeviceStore.java
index 44fc843b..db10fcfa 100644
--- a/src/com/connectsdk/device/ConnectableDeviceStore.java
+++ b/src/com/connectsdk/device/ConnectableDeviceStore.java
@@ -63,7 +63,7 @@ public interface ConnectableDeviceStore {
public void updateDevice(ConnectableDevice device);
/**
- * A JSONObject of all ConnectableDevices in the ConnectableDeviceStore. To gt a strongly-typed ConnectableDevice object, use the `getDevice(String);` method.
+ * @return a JSONObject of all ConnectableDevices in the ConnectableDeviceStore. To get a strongly-typed ConnectableDevice object, use the `getDevice(String);` method.
*/
public JSONObject getStoredDevices();
diff --git a/src/com/connectsdk/device/DefaultConnectableDeviceStore.java b/src/com/connectsdk/device/DefaultConnectableDeviceStore.java
index 6ff0b0f4..c0899774 100644
--- a/src/com/connectsdk/device/DefaultConnectableDeviceStore.java
+++ b/src/com/connectsdk/device/DefaultConnectableDeviceStore.java
@@ -21,10 +21,18 @@
package com.connectsdk.device;
import java.io.BufferedReader;
+import java.io.BufferedWriter;
import java.io.File;
+import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.InputStreamReader;
+import java.io.Writer;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.io.FileOutputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@@ -33,10 +41,8 @@
import org.json.JSONException;
import org.json.JSONObject;
-import android.content.Context;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.os.Environment;
-
+import com.connectsdk.core.Context;
+import com.connectsdk.core.Log;
import com.connectsdk.core.Util;
import com.connectsdk.service.DeviceService;
import com.connectsdk.service.config.ServiceConfig;
@@ -88,10 +94,6 @@ public class DefaultConnectableDeviceStore implements ConnectableDeviceStore {
/** Current version of the ConnectableDeviceStore, may be necessary for migrations */
public int version;
- /**
- * Max length of time for a ConnectableDevice to remain in the ConnectableDeviceStore without being discovered. Default is 3 days, and modifications to this value will trigger a scan for old devices.
- */
- public long maxStoreDuration = TimeUnit.DAYS.toSeconds(3);
// @cond INTERNAL
private String fileFullPath;
@@ -99,24 +101,9 @@ public class DefaultConnectableDeviceStore implements ConnectableDeviceStore {
private Map storedDevices = new ConcurrentHashMap();
private Map activeDevices = new ConcurrentHashMap();
- private boolean waitToWrite = false;
-
public DefaultConnectableDeviceStore(Context context) {
- String dirPath;
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- dirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
- }
- else {
- dirPath = Environment.MEDIA_UNMOUNTED;
- }
- fileFullPath = dirPath + DIRPATH + FILENAME;
-
- try {
- fileFullPath = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir + "/" + FILENAME;
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
-
+ fileFullPath = context.getDataDir() + "/" + FILENAME;
+
load();
}
// @endcond
@@ -289,29 +276,21 @@ public ServiceConfig getServiceConfig(ServiceDescription serviceDescription) {
private void load() {
String line;
- BufferedReader in = null;
-
File file = new File(fileFullPath);
if (!file.exists()) {
version = CURRENT_VERSION;
-
created = Util.getTime();
updated = Util.getTime();
} else {
- boolean encounteredException = false;
-
- try {
- in = new BufferedReader(new FileReader(file));
-
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))){
+
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
- in.close();
-
JSONObject data = new JSONObject(sb.toString());
JSONArray deviceArray = data.optJSONArray(KEY_DEVICES);
if (deviceArray != null) {
@@ -324,32 +303,22 @@ private void load() {
version = data.optInt(KEY_VERSION, CURRENT_VERSION);
created = data.optLong(KEY_CREATED, 0);
updated = data.optLong(KEY_UPDATED, 0);
- } catch (IOException e) {
+ } catch (IOException|JSONException e) {
e.printStackTrace();
-
- // it is likely that the device store has been corrupted
- encounteredException = true;
- } catch (JSONException e) {
- e.printStackTrace();
-
- // it is likely that the device store has been corrupted
- encounteredException = true;
- }
-
- if (encounteredException && storedDevices == null) {
- file.delete();
-
- version = CURRENT_VERSION;
-
- created = Util.getTime();
- updated = Util.getTime();
- }
+ }
}
}
- private void store() {
+ private synchronized void store() {
updated = Util.getTime();
+ File output = new File(fileFullPath);
+
+ if (!output.exists() && !output.getParentFile().mkdirs()) {
+ Log.e(Util.T, "Failed to create folders structure to device store "+output.getParentFile().toString());
+ return;
+ }
+
JSONObject deviceStore = new JSONObject();
try {
deviceStore.put(KEY_VERSION, version);
@@ -357,42 +326,16 @@ private void store() {
deviceStore.put(KEY_UPDATED, updated);
JSONArray deviceArray = new JSONArray(storedDevices.values());
deviceStore.put(KEY_DEVICES, deviceArray);
- } catch (JSONException e) {
+
+
+ try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), StandardCharsets.UTF_8))) {
+ out.write(deviceStore.toString());
+ }
+ } catch (JSONException|IOException e) {
e.printStackTrace();
- }
-
- if (!waitToWrite)
- writeStoreToDisk(deviceStore);
+ }
}
- private synchronized void writeStoreToDisk(final JSONObject deviceStore) {
- final long lastUpdate = updated;
- waitToWrite = true;
-
- Util.runInBackground(new Runnable() {
-
- @Override
- public void run() {
- FileWriter out;
- try {
- File output = new File(fileFullPath);
-
- if (!output.exists())
- output.getParentFile().mkdirs();
- out = new FileWriter(output);
- out.write(deviceStore.toString());
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- waitToWrite = false;
- }
-
- if (lastUpdate < updated)
- writeStoreToDisk(deviceStore);
- }
- });
- }
// @endcond
}
diff --git a/src/com/connectsdk/device/DevicePicker.java b/src/com/connectsdk/device/DevicePicker.java
deleted file mode 100644
index 9e4c655b..00000000
--- a/src/com/connectsdk/device/DevicePicker.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * DevicePicker
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Created by Hyun Kook Khang on 19 Jan 2014
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.device;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.ListView;
-import android.widget.TextView;
-
-/**
- * ###Overview
- * The DevicePicker is provided by the DiscoveryManager as a simple way for you to present a list of available devices to your users.
- *
- * ###In Depth
- * By calling the getPickerDialog you will get a reference to the AlertDialog that will be updated automatically updated as compatible devices are discovered.
- */
-public class DevicePicker {
- Activity activity;
- ConnectableDevice device;
-
- /**
- * Creates a new DevicePicker
- *
- * @param activity Activity that DevicePicker will appear in
- */
- public DevicePicker(Activity activity) {
- this.activity = activity;
- }
-
- public ListView getListView() {
- return new DevicePickerListView(activity);
- }
-
- /**
- * Sets a selected device.
- *
- * @param device Device that has been selected.
- */
- public void pickDevice(ConnectableDevice device) {
- this.device = device;
- }
-
- /**
- * Cancels pairing with the currently selected device.
- */
- public void cancelPicker() {
- if (device != null) {
- device.cancelPairing();
- }
- device = null;
- }
-
- /**
- * This method will return an AlertDialog that contains a ListView with an item for each discovered ConnectableDevice.
- *
- * @param message The title for the AlertDialog
- * @param listener The listener for the ListView to get the item that was clicked on
- */
- public AlertDialog getPickerDialog(String message, final OnItemClickListener listener) {
- final DevicePickerListView view = new DevicePickerListView(activity);
-
- TextView title = (TextView) activity.getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
- title.setText(message);
-
- final AlertDialog pickerDialog = new AlertDialog.Builder(activity)
- .setCustomTitle(title)
- .setCancelable(true)
- .setView(view)
- .create();
-
- view.setOnItemClickListener(new OnItemClickListener () {
- @Override
- public void onItemClick(AdapterView> arg0, View arg1, int arg2,
- long arg3) {
- listener.onItemClick(arg0, arg1, arg2, arg3);
- pickerDialog.dismiss();
- }
- });
-
- return pickerDialog;
- }
-}
diff --git a/src/com/connectsdk/device/DevicePickerAdapter.java b/src/com/connectsdk/device/DevicePickerAdapter.java
deleted file mode 100644
index 48010a41..00000000
--- a/src/com/connectsdk/device/DevicePickerAdapter.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * DevicePickerAdaper
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Created by Hyun Kook Khang on 19 Jan 2014
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.device;
-
-import java.util.HashMap;
-
-import com.connectsdk.discovery.DiscoveryManager;
-
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.graphics.Color;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.TextView;
-
-
-public class DevicePickerAdapter extends ArrayAdapter {
- int resource, textViewResourceId, subTextViewResourceId;
- HashMap currentDevices = new HashMap();
- Context context;
-
- DevicePickerAdapter(Context context) {
- this(context, android.R.layout.simple_list_item_2);
- }
-
- DevicePickerAdapter(Context context, int resource) {
- this(context, resource, android.R.id.text1, android.R.id.text2);
- }
-
- DevicePickerAdapter(Context context, int resource, int textViewResourceId, int subTextViewResourceId) {
- super(context, resource, textViewResourceId);
- this.context = context;
- this.resource = resource;
- this.textViewResourceId = textViewResourceId;
- this.subTextViewResourceId = subTextViewResourceId;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- View view = convertView;
-
- if (convertView == null) {
- view = View.inflate(getContext(), resource, null);
- }
-
- ConnectableDevice device = this.getItem(position);
- String text;
- if (device.getFriendlyName() != null) {
- text = device.getFriendlyName();
- }
- else {
- text = device.getModelName();
- }
-
- view.setBackgroundColor(Color.BLACK);
-
- TextView textView = (TextView) view.findViewById(textViewResourceId);
- textView.setText(text);
- textView.setTextColor(Color.WHITE);
-
- boolean isDebuggable = (0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
- boolean hasNoFilters = DiscoveryManager.getInstance().getCapabilityFilters().size() == 0;
-
- String serviceNames = device.getConnectedServiceNames();
- boolean hasServiceNames = (serviceNames != null && serviceNames.length() > 0);
-
- boolean shouldShowServiceNames = hasServiceNames && (isDebuggable || hasNoFilters);
-
- TextView subTextView = (TextView) view.findViewById(subTextViewResourceId);
-
- if (shouldShowServiceNames) {
- subTextView.setText(serviceNames);
- subTextView.setTextColor(Color.WHITE);
- } else {
- subTextView.setText(null);
- }
-
- return view;
- }
-}
diff --git a/src/com/connectsdk/device/DevicePickerListView.java b/src/com/connectsdk/device/DevicePickerListView.java
deleted file mode 100644
index 373a9c8a..00000000
--- a/src/com/connectsdk/device/DevicePickerListView.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * DevicePickerListView
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Created by Hyun Kook Khang on 19 Jan 2014
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.device;
-
-import android.content.Context;
-import android.widget.ListView;
-
-import com.connectsdk.core.Util;
-import com.connectsdk.discovery.DiscoveryManager;
-import com.connectsdk.discovery.DiscoveryManagerListener;
-import com.connectsdk.service.command.ServiceCommandError;
-
-public class DevicePickerListView extends ListView implements DiscoveryManagerListener {
- DevicePickerAdapter pickerAdapter;
-
- public DevicePickerListView(Context context) {
- super(context);
-
- pickerAdapter = new DevicePickerAdapter(context);
-
- setAdapter(pickerAdapter);
-
- DiscoveryManager.getInstance().addListener(this);
- }
-
- @Override
- public void onDiscoveryFailed(DiscoveryManager manager, ServiceCommandError error) {
- Util.runOnUI(new Runnable () {
- @Override
- public void run() {
- pickerAdapter.clear();
- }
- });
- }
-
- @Override
- public void onDeviceAdded(DiscoveryManager manager, final ConnectableDevice device) {
- Util.runOnUI(new Runnable () {
- @Override
- public void run() {
- int index = -1;
- for (int i = 0; i < pickerAdapter.getCount(); i++) {
- ConnectableDevice d = pickerAdapter.getItem(i);
-
- String newDeviceName = device.getFriendlyName();
- String dName = d.getFriendlyName();
-
- if (newDeviceName == null) {
- newDeviceName = device.getModelName();
- }
-
- if (dName == null) {
- dName = d.getModelName();
- }
-
- if (d.getIpAddress().equals(device.getIpAddress())) {
- pickerAdapter.remove(d);
- pickerAdapter.insert(device, i);
- return;
- }
-
- if (newDeviceName.compareToIgnoreCase(dName) < 0) {
- index = i;
- pickerAdapter.insert(device, index);
- break;
- }
- }
-
- if (index == -1)
- pickerAdapter.add(device);
- }
- });
- }
-
- @Override
- public void onDeviceUpdated(DiscoveryManager manager, final ConnectableDevice device) {
- Util.runOnUI(new Runnable () {
- @Override
- public void run() {
- pickerAdapter.notifyDataSetChanged();
- }
- });
- }
-
- @Override
- public void onDeviceRemoved(DiscoveryManager manager, final ConnectableDevice device) {
- Util.runOnUI(new Runnable () {
- @Override
- public void run() {
- pickerAdapter.remove(device);
- }
- });
- }
-}
diff --git a/src/com/connectsdk/device/DevicePickerListener.java b/src/com/connectsdk/device/DevicePickerListener.java
index 08e08073..f5d57d01 100644
--- a/src/com/connectsdk/device/DevicePickerListener.java
+++ b/src/com/connectsdk/device/DevicePickerListener.java
@@ -3,13 +3,13 @@
public interface DevicePickerListener {
/**
* Called when the user selects a device.
- * @param device
+ * @param device the selected device
*/
public void onPickDevice(ConnectableDevice device);
/**
* Called when the picker fails or was cancelled by the user.
- * @param true if picker was canceled by user, false if due to error
+ * @param canceled true if picker was canceled by user, false if due to error
*/
public void onPickDeviceFailed(boolean canceled);
}
diff --git a/src/com/connectsdk/device/PairingDialog.java b/src/com/connectsdk/device/PairingDialog.java
deleted file mode 100644
index c066e1cd..00000000
--- a/src/com/connectsdk/device/PairingDialog.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * PairingDialog
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Created by Hyun Kook Khang on 19 Jan 2014
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.device;
-
-import com.connectsdk.service.DeviceService;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.text.InputType;
-import android.widget.EditText;
-import android.widget.TextView;
-
-
-public class PairingDialog {
- Activity activity;
- ConnectableDevice device;
-
- public PairingDialog(Activity activity, ConnectableDevice device) {
- this.activity = activity;
- this.device = device;
- }
-
- public AlertDialog getSimplePairingDialog(int titleResId, int messageResId) {
- return new AlertDialog.Builder(activity)
- .setTitle(titleResId)
- .setMessage(messageResId)
- .setPositiveButton(android.R.string.cancel, null)
- .create();
- }
-
- public AlertDialog getPairingDialog(int resId) {
- return getPairingDialog(activity.getString(resId));
- }
-
- public AlertDialog getPairingDialog(String message) {
- TextView title = (TextView) activity.getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
- title.setText(message);
-
- final EditText input = new EditText(activity);
- input.setInputType(InputType.TYPE_CLASS_NUMBER);
-
- return new AlertDialog.Builder(activity)
- .setCustomTitle(title)
- .setView(input)
- .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- String value = input.getText().toString().trim();
- for (DeviceService service : device.getServices())
- service.sendPairingKey(value);
- }
- })
- .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- dialog.cancel();
- // pickerDialog.dismiss();
- }
- })
- .create();
- }
-}
diff --git a/src/com/connectsdk/device/SimpleDevicePicker.java b/src/com/connectsdk/device/SimpleDevicePicker.java
deleted file mode 100644
index 4aa3aeac..00000000
--- a/src/com/connectsdk/device/SimpleDevicePicker.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * SimpleDevicePicker
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Created by Jason Lai on 19 Jan 2014
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.device;
-
-import java.util.List;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.content.res.Resources;
-import android.util.Log;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.Toast;
-
-import com.connectsdk.core.Util;
-import com.connectsdk.service.DeviceService;
-import com.connectsdk.service.DeviceService.PairingType;
-import com.connectsdk.service.command.ServiceCommandError;
-
-/**
- * A device picker that automatically connects to the device
- * and automatically displays pairing dialogs when needed.
- *
- * NOTE: Most methods MUST be called from the main ui thread.
- */
-public class SimpleDevicePicker implements ConnectableDeviceListener {
- protected Activity activity;
- protected DevicePicker picker;
- protected Dialog pickerDialog;
- protected Dialog pairingDialog;
-
- // Device that we're in the process of connecting to
- protected ConnectableDevice pendingDevice;
-
- // Connected, active device
- protected ConnectableDevice activeDevice;
-
- protected int selectDeviceResId;
- protected int simplePairingTitleResId;
- protected int simplePairingPromptResId;
- protected int pinPairingPromptResId;
- protected int connectionFailedResId;
-
- SimpleDevicePickerListener listener;
- private PairingType pairingType;
-
- public SimpleDevicePicker(Activity activity) {
- this.activity = activity;
- this.picker = new DevicePicker(activity);
-
- loadStringIds();
- }
-
- public void setPairingType(PairingType pairingType) {
- this.pairingType = pairingType;
- }
-
- /**
- * Get the currently selected device
- * @return current connected device
- */
- public ConnectableDevice getCurrentDevice() {
- return activeDevice;
- }
-
- protected void loadStringIds() {
- selectDeviceResId = getStringId("connect_sdk_picker_select_device");
- simplePairingTitleResId = getStringId("connect_sdk_pairing_simple_title_tv");
- simplePairingPromptResId = getStringId("connect_sdk_pairing_simple_prompt_tv");
- pinPairingPromptResId = getStringId("connect_sdk_pairing_pin_prompt_tv");
- connectionFailedResId = getStringId("connect_sdk_connection_failed");
- }
-
- protected int getStringId(String key) {
- // First try to get resource from application
- int id = this.activity.getResources().getIdentifier(key, "string", activity.getPackageName());
-
- // Then try to get from Connect SDK library
- if (id == 0) {
- id = this.activity.getResources().getIdentifier(key, "string", "com.connectsdk");
- }
-
- if (id == 0) {
- Log.w("ConnectSDK", "missing string resource for \"" + key + "\"");
-
- throw new Resources.NotFoundException(key);
- }
-
- return id;
- }
-
- public void setListener(SimpleDevicePickerListener listener) {
- this.listener = listener;
- }
-
- protected void cleanupPending() {
- if (pendingDevice != null) {
- pendingDevice.removeListener(this);
- pendingDevice = null;
- }
- }
-
- protected void cleanupActive() {
- if (activeDevice != null) {
- activeDevice.removeListener(this);
- activeDevice = null;
- }
- }
-
- public void showPicker() {
- cleanupPending(); // remove any currently pending device
- hidePicker();
-
- pickerDialog = picker.getPickerDialog(activity.getString(selectDeviceResId), new OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView> adapter, View view, int pos,
- long id) {
- ConnectableDevice device = (ConnectableDevice) adapter.getItemAtPosition(pos);
-
- selectDevice(device);
- }
- });
-
- pickerDialog.show();
- }
-
- public void hidePicker() {
- if (pickerDialog != null) {
- pickerDialog.dismiss();
- pickerDialog = null;
- }
- }
-
- /**
- * Connect to a device
- *
- * @param device
- */
- public void selectDevice(ConnectableDevice device) {
- if (device != null) {
- pendingDevice = device;
- pendingDevice.addListener(this);
-
- if (listener != null) {
- // Give listener a chance to setup device before connecting
- listener.onPrepareDevice(device);
- }
-
- if (!device.isConnected()) {
- device.setPairingType(pairingType);
- device.connect();
- } else {
- onDeviceReady(device);
- }
- } else {
- cleanupPending();
- }
- }
-
- protected Dialog createSimplePairingDialog() {
- PairingDialog dialog = new PairingDialog(activity, pendingDevice);
- return dialog.getSimplePairingDialog(simplePairingTitleResId, simplePairingPromptResId);
- }
-
- protected Dialog createPinPairingDialog() {
- PairingDialog dialog = new PairingDialog(activity, pendingDevice);
- return dialog.getPairingDialog(pinPairingPromptResId);
- }
-
- protected void showPairingDialog(PairingType pairingType) {
- switch (pairingType) {
- case FIRST_SCREEN:
- pairingDialog = createSimplePairingDialog();
- break;
-
- case PIN_CODE:
- case MIXED:
- pairingDialog = createPinPairingDialog();
- break;
-
- case NONE:
- default:
- break;
- }
-
- if (pairingDialog != null) {
- pairingDialog.show();
- }
- }
-
- /**
- * Hide the current pairing dialog and cancels the pairing attempt.
- */
- public void hidePairingDialog() {
- // cancel pairing
- if (pairingDialog != null) {
- pairingDialog.dismiss();
- pairingDialog = null;
- }
- }
-
-
- @Override
- public void onDeviceReady(final ConnectableDevice device) {
- Util.runOnUI(new Runnable() {
- @Override
- public void run() {
- hidePairingDialog();
-
- if (device == pendingDevice) {
- activeDevice = pendingDevice;
-
- if (listener != null) {
- listener.onPickDevice(pendingDevice);
- }
- pendingDevice = null;
- }
- }
- });
- }
-
- @Override
- public void onDeviceDisconnected(final ConnectableDevice device) {
- if (device == pendingDevice) {
- pickFailed(device);
- }
-
- if (device == activeDevice) {
- cleanupActive();
- }
- }
-
- @Override
- public void onCapabilityUpdated(ConnectableDevice device, List added, List removed) {
- }
-
- @Override
- public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) {
- if (device == pendingDevice) {
- pickFailed(device);
- }
-
- if (device == activeDevice) {
- cleanupActive();
- }
- }
-
- @Override
- public void onPairingRequired(ConnectableDevice device, DeviceService service, final PairingType pairingType) {
- Log.d("SimpleDevicePicker", "pairing required for device " + device.getFriendlyName());
-
- Util.runOnUI(new Runnable() {
- @Override
- public void run() {
- showPairingDialog(pairingType);
- }
- });
- }
-
- protected void pickFailed(final ConnectableDevice device) {
- Util.runOnUI(new Runnable() {
- @Override
- public void run() {
- if (pendingDevice == device) {
- // Device failed before successfully picking device
- if (listener != null) {
- listener.onPickDeviceFailed(false);
- }
- }
-
- cleanupPending();
-
- Toast.makeText(activity, connectionFailedResId, Toast.LENGTH_SHORT).show();
- }
- });
- }
-}
diff --git a/src/com/connectsdk/device/SimpleDevicePickerListener.java b/src/com/connectsdk/device/SimpleDevicePickerListener.java
index 6d5ddd47..3182602c 100644
--- a/src/com/connectsdk/device/SimpleDevicePickerListener.java
+++ b/src/com/connectsdk/device/SimpleDevicePickerListener.java
@@ -6,20 +6,20 @@ public interface SimpleDevicePickerListener extends DevicePickerListener {
* This callback can be used to prepare the device (request permissions, etc)
* just before attempting to connect.
*
- * @param device
+ * @param device selected device
*/
public void onPrepareDevice(ConnectableDevice device);
/**
* Called when device is ready to use (requested permissions approved).
- * @param device
+ * @param device that is ready to use
*/
public void onPickDevice(ConnectableDevice device);
/**
* Called when the picker is canceled by the user or if pairing
* was unsuccessful.
- * @param true if picker was canceled by user, false if due to error
+ * @param canceled true if picker was canceled by user, false if due to error
*/
public void onPickDeviceFailed(boolean canceled);
}
diff --git a/src/com/connectsdk/discovery/CapabilityFilter.java b/src/com/connectsdk/discovery/CapabilityFilter.java
index f9e99745..3c558a6a 100644
--- a/src/com/connectsdk/discovery/CapabilityFilter.java
+++ b/src/com/connectsdk/discovery/CapabilityFilter.java
@@ -44,34 +44,32 @@
*
* ###Examples
* Filter for all devices that support video playback AND any media controls AND volume up/down.
- *
-@code
- List capabilities = new ArrayList();
- capabilities.add(MediaPlayer.Display_Video);
- capabilities.add(MediaControl.Any);
- capabilities.add(VolumeControl.Volume_Up_Down);
-
- CapabilityFilter filter =
- new CapabilityFilter(capabilities);
-
- DiscoveryManager.getInstance().setCapabilityFilters(filter);
-@endcode
+ *
+ * List<String> capabilities = new ArrayList<String>();
+ * capabilities.add(MediaPlayer.Display_Video);
+ * capabilities.add(MediaControl.Any);
+ * capabilities.add(VolumeControl.Volume_Up_Down);
+ *
+ * CapabilityFilter filter =
+ * new CapabilityFilter(capabilities);
+ *
+ * DiscoveryManager.getInstance().setCapabilityFilters(filter);
+ *
*
* Filter for all devices that support (video playback AND any media controls AND volume up/down) OR (image display).
+ *
+ * CapabilityFilter videoFilter =
+ * new CapabilityFilter(
+ * MediaPlayer.Display_Video,
+ * MediaControl.Any,
+ * VolumeControl.Volume_Up_Down);
*
-@code
- CapabilityFilter videoFilter =
- new CapabilityFilter(
- MediaPlayer.Display_Video,
- MediaControl.Any,
- VolumeControl.Volume_Up_Down);
-
- CapabilityFilter imageFilter =
- new CapabilityFilter(
- MediaPlayer.Display_Image);
-
- DiscoveryManager.getInstance().setCapabilityFilters(videoFilter, imageFilter);
-@endcode
+ * CapabilityFilter imageFilter =
+ * new CapabilityFilter(
+ * MediaPlayer.Display_Image);
+ *
+ * DiscoveryManager.getInstance().setCapabilityFilters(videoFilter, imageFilter);
+ *
*/
public class CapabilityFilter {
diff --git a/src/com/connectsdk/discovery/DiscoveryManager.java b/src/com/connectsdk/discovery/DiscoveryManager.java
index 21b26d98..7dc29d1d 100644
--- a/src/com/connectsdk/discovery/DiscoveryManager.java
+++ b/src/com/connectsdk/discovery/DiscoveryManager.java
@@ -1,10 +1,10 @@
/*
* DiscoveryManager
* Connect SDK
- *
+ *
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 19 Jan 2014
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -33,17 +33,8 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.wifi.WifiManager;
-import android.net.wifi.WifiManager.MulticastLock;
-import android.util.Log;
-
-import com.connectsdk.DefaultPlatform;
+import com.connectsdk.core.Context;
+import com.connectsdk.core.Log;
import com.connectsdk.core.Util;
import com.connectsdk.device.ConnectableDevice;
import com.connectsdk.device.ConnectableDeviceListener;
@@ -61,29 +52,36 @@
/**
* ###Overview
*
- * At the heart of Connect SDK is DiscoveryManager, a multi-protocol service discovery engine with a pluggable architecture. Much of your initial experience with Connect SDK will be with the DiscoveryManager class, as it consolidates discovered service information into ConnectableDevice objects.
+ * At the heart of Connect SDK is DiscoveryManager, a multi-protocol service discovery engine with a pluggable
+ * architecture. Much of your initial experience with Connect SDK will be with the DiscoveryManager class, as it
+ * consolidates discovered service information into ConnectableDevice objects.
*
* ###In depth
- * DiscoveryManager supports discovering services of differing protocols by using DiscoveryProviders. Many services are discoverable over [SSDP][0] and are registered to be discovered with the SSDPDiscoveryProvider class.
+ * DiscoveryManager supports discovering services of differing protocols by using DiscoveryProviders. Many services are
+ * discoverable over [SSDP][0] and are registered to be discovered with the SSDPDiscoveryProvider class.
*
- * As services are discovered on the network, the DiscoveryProviders will notify DiscoveryManager. DiscoveryManager is capable of attributing multiple services, if applicable, to a single ConnectableDevice instance. Thus, it is possible to have a mixed-mode ConnectableDevice object that is theoretically capable of more functionality than a single service can provide.
+ * As services are discovered on the network, the DiscoveryProviders will notify DiscoveryManager. DiscoveryManager is
+ * capable of attributing multiple services, if applicable, to a single ConnectableDevice instance. Thus, it is possible
+ * to have a mixed-mode ConnectableDevice object that is theoretically capable of more functionality than a single
+ * service can provide.
*
- * DiscoveryManager keeps a running list of all discovered devices and maintains a filtered list of devices that have satisfied any of your CapabilityFilters. This filtered list is used by the DevicePicker when presenting the user with a list of devices.
+ * DiscoveryManager keeps a running list of all discovered devices and maintains a filtered list of devices that have
+ * satisfied any of your CapabilityFilters. This filtered list is used by the DevicePicker when presenting the user with
+ * a list of devices.
*
- * Only one instance of the DiscoveryManager should be in memory at a time. To assist with this, DiscoveryManager has static method at sharedManager.
+ * Only one instance of the DiscoveryManager should be in memory at a time. To assist with this, DiscoveryManager has
+ * static method at sharedManager.
*
* Example:
*
- * @capability kMediaControlPlay
- *
- @code
- DiscoveryManager.init(getApplicationContext());
- DiscoveryManager discoveryManager = DiscoveryManager.getInstance();
- discoveryManager.addListener(this);
- discoveryManager.start();
- @endcode
+ *
+ * DiscoveryManager.init(getApplicationContext());
+ * DiscoveryManager discoveryManager = DiscoveryManager.getInstance();
+ * discoveryManager.addListener(this);
+ * discoveryManager.start();
+ *
*
- * [0]: http://tools.ietf.org/html/draft-cai-ssdp-v1-03
+ * [0]: http://tools.ietf.org/html/draft-cai-ssdp-v1-03
*/
public class DiscoveryManager implements ConnectableDeviceListener, DiscoveryProviderListener, ServiceConfigListener {
@@ -107,15 +105,13 @@ public enum PairingLevel {
// @cond INTERNAL
- public static String CONNECT_SDK_VERSION = "1.6.0";
+ public static final String CONNECT_SDK_VERSION = "1.6.0";
private static DiscoveryManager instance;
Context context;
ConnectableDeviceStore connectableDeviceStore;
- int rescanInterval = 10;
-
private ConcurrentHashMap allDevices;
private ConcurrentHashMap compatibleDevices;
@@ -125,24 +121,22 @@ public enum PairingLevel {
private CopyOnWriteArrayList discoveryListeners;
List capabilityFilters;
- MulticastLock multicastLock;
- BroadcastReceiver receiver;
- boolean isBroadcastReceiverRegistered = false;
-
- Timer rescanTimer;
-
- PairingLevel pairingLevel;
+
+ private PairingLevel pairingLevel;
private boolean mSearching = false;
// @endcond
/**
- * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use getApplicationContext() as the Discovery manager could persist longer than the current Activity.
+ * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use
+ * getApplicationContext() as the Discovery manager could persist longer than the current Activity.
*
- @code
- DiscoveryManager.init(getApplicationContext());
- @endcode
+ *
+ * DiscoveryManager.init(getApplicationContext());
+ *
+ *
+ * @param context a valid context
*/
public static synchronized void init(Context context) {
instance = new DiscoveryManager(context);
@@ -153,25 +147,30 @@ public static synchronized void destroy() {
}
/**
- * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use getApplicationContext() as the Discovery manager could persist longer than the current Activity.
- *
+ * Initilizes the Discovery manager with a valid context. This should be done as soon as possible and it should use
+ * getApplicationContext() as the Discovery manager could persist longer than the current Activity.
+ *
* This accepts a ConnectableDeviceStore to use instead of the default device store.
*
- @code
- MyConnectableDeviceStore myDeviceStore = new MyConnectableDeviceStore();
- DiscoveryManager.init(getApplicationContext(), myDeviceStore);
- @endcode
+ *
+ * MyConnectableDeviceStore myDeviceStore = new MyConnectableDeviceStore();
+ * DiscoveryManager.init(getApplicationContext(), myDeviceStore);
+ *
+ *
+ * @param context a valid context
+ * @param connectableDeviceStore a device store
*/
public static synchronized void init(Context context, ConnectableDeviceStore connectableDeviceStore) {
instance = new DiscoveryManager(context, connectableDeviceStore);
}
/**
- * Get a shared instance of DiscoveryManager.
+ * @return a shared instance of DiscoveryManager.
*/
public static synchronized DiscoveryManager getInstance() {
- if (instance == null)
+ if (instance == null) {
throw new Error("Call DiscoveryManager.init(Context) first");
+ }
return instance;
}
@@ -181,6 +180,7 @@ public static synchronized DiscoveryManager getInstance() {
* Create a new instance of DiscoveryManager.
* Direct use of this constructor is not recommended. In most cases,
* you should use DiscoveryManager.getInstance() instead.
+ * @param context a valid context
*/
public DiscoveryManager(Context context) {
this(context, new DefaultConnectableDeviceStore(context));
@@ -190,6 +190,9 @@ public DiscoveryManager(Context context) {
* Create a new instance of DiscoveryManager.
* Direct use of this constructor is not recommended. In most cases,
* you should use DiscoveryManager.getInstance() instead.
+ *
+ * @param context a valid context
+ * @param connectableDeviceStore a device store
*/
public DiscoveryManager(Context context, ConnectableDeviceStore connectableDeviceStore) {
this.context = context;
@@ -203,91 +206,97 @@ public DiscoveryManager(Context context, ConnectableDeviceStore connectableDevic
discoveryListeners = new CopyOnWriteArrayList();
- WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
- multicastLock = wifiMgr.createMulticastLock(Util.T);
- multicastLock.setReferenceCounted(true);
+// WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
+// multicastLock = wifiMgr.createMulticastLock(Util.T);
+// multicastLock.setReferenceCounted(true);
capabilityFilters = new ArrayList();
pairingLevel = PairingLevel.OFF;
- receiver = new BroadcastReceiver() {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
-
- if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
- NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
-
- switch (networkInfo.getState()) {
- case CONNECTED:
- if (mSearching) {
- for (DiscoveryProvider provider : discoveryProviders) {
- provider.restart();
- }
- }
-
- break;
-
- case DISCONNECTED:
- Log.w(Util.T, "Network connection is disconnected");
-
- for (DiscoveryProvider provider : discoveryProviders) {
- provider.reset();
- }
-
- allDevices.clear();
-
- for (ConnectableDevice device: compatibleDevices.values()) {
- handleDeviceLoss(device);
- }
- compatibleDevices.clear();
-
- break;
-
- case CONNECTING:
- break;
- case DISCONNECTING:
- break;
- case SUSPENDED:
- break;
- case UNKNOWN:
- break;
- }
- }
- }
- };
-
- registerBroadcastReceiver();
+// receiver = new BroadcastReceiver() {
+//
+// @Override
+// public void onReceive(Context context, Intent intent) {
+// String action = intent.getAction();
+//
+// if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
+// NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
+//
+// switch (networkInfo.getState()) {
+// case CONNECTED:
+// if (mSearching) {
+// for (DiscoveryProvider provider : discoveryProviders) {
+// provider.restart();
+// }
+// }
+//
+// break;
+//
+// case DISCONNECTED:
+// Log.w(Util.T, "Network connection is disconnected");
+//
+// for (DiscoveryProvider provider : discoveryProviders) {
+// provider.reset();
+// }
+//
+// allDevices.clear();
+//
+// for (ConnectableDevice device : compatibleDevices.values()) {
+// handleDeviceLoss(device);
+// }
+// compatibleDevices.clear();
+//
+// break;
+//
+// case CONNECTING:
+// break;
+// case DISCONNECTING:
+// break;
+// case SUSPENDED:
+// break;
+// case UNKNOWN:
+// break;
+// }
+// }
+// }
+// };
+
+ //registerBroadcastReceiver();
}
// @endcond
- private void registerBroadcastReceiver() {
- if (!isBroadcastReceiverRegistered) {
- isBroadcastReceiverRegistered = true;
-
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- context.registerReceiver(receiver, intentFilter);
- }
- }
-
- private void unregisterBroadcastReceiver() {
- if (isBroadcastReceiverRegistered) {
- isBroadcastReceiverRegistered = false;
-
- context.unregisterReceiver(receiver);
- }
- }
+// private void registerBroadcastReceiver() {
+// if (!isBroadcastReceiverRegistered) {
+// isBroadcastReceiverRegistered = true;
+//
+// IntentFilter intentFilter = new IntentFilter();
+// intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
+// context.registerReceiver(receiver, intentFilter);
+// }
+// }
+//
+// private void unregisterBroadcastReceiver() {
+// if (isBroadcastReceiverRegistered) {
+// isBroadcastReceiverRegistered = false;
+//
+// context.unregisterReceiver(receiver);
+// }
+// }
/**
- * Listener which should receive discovery updates. It is not necessary to set this listener property unless you are implementing your own device picker. Connect SDK provides a default DevicePicker which acts as a DiscoveryManagerListener, and should work for most cases.
+ * It is not necessary to set this listener property unless you are
+ * implementing your own device picker. Connect SDK provides a default DevicePicker which acts as a
+ * DiscoveryManagerListener, and should work for most cases.
*
- * If you have provided a capabilityFilters array, the listener will only receive update messages for ConnectableDevices which satisfy at least one of the CapabilityFilters. If no capabilityFilters array is provided, the listener will receive update messages for all ConnectableDevice objects that are discovered.
+ * If you have provided a capabilityFilters array, the listener will only receive update messages for
+ * ConnectableDevices which satisfy at least one of the CapabilityFilters. If no capabilityFilters array is
+ * provided, the listener will receive update messages for all ConnectableDevice objects that are discovered.
+ *
+ * @param listener Listener which should receive discovery updates
*/
public void addListener(DiscoveryManagerListener listener) {
// notify listener of all devices so far
- for (ConnectableDevice device: compatibleDevices.values()) {
+ for (ConnectableDevice device : compatibleDevices.values()) {
listener.onDeviceAdded(this, device);
}
discoveryListeners.add(listener);
@@ -295,25 +304,27 @@ public void addListener(DiscoveryManagerListener listener) {
/**
* Removes a previously added listener
+ *
+ * @param listener Listener which should be removed
*/
public void removeListener(DiscoveryManagerListener listener) {
discoveryListeners.remove(listener);
}
- public void setCapabilityFilters(CapabilityFilter ... capabilityFilters) {
+ public void setCapabilityFilters(CapabilityFilter... capabilityFilters) {
setCapabilityFilters(Arrays.asList(capabilityFilters));
}
public void setCapabilityFilters(List capabilityFilters) {
this.capabilityFilters = capabilityFilters;
- for (ConnectableDevice device: compatibleDevices.values()) {
+ for (ConnectableDevice device : compatibleDevices.values()) {
handleDeviceLoss(device);
}
compatibleDevices.clear();
- for (ConnectableDevice device: allDevices.values()) {
+ for (ConnectableDevice device : allDevices.values()) {
if (deviceIsCompatible(device)) {
compatibleDevices.put(device.getIpAddress(), device);
@@ -323,7 +334,7 @@ public void setCapabilityFilters(List capabilityFilters) {
}
/**
- * Returns the list of capability filters.
+ * @return the list of capability filters.
*/
public List getCapabilityFilters() {
return capabilityFilters;
@@ -336,7 +347,7 @@ public boolean deviceIsCompatible(ConnectableDevice device) {
boolean isCompatible = false;
- for (CapabilityFilter filter: this.capabilityFilters) {
+ for (CapabilityFilter filter : this.capabilityFilters) {
if (device.hasCapabilities(filter.capabilities)) {
isCompatible = true;
break;
@@ -348,29 +359,47 @@ public boolean deviceIsCompatible(ConnectableDevice device) {
// @cond INTERNAL
/**
- * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call of startDiscovery if no DeviceServices have been registered.
+ * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call
+ * of startDiscovery if no DeviceServices have been registered.
*
* - CastDiscoveryProvider
- * + CastService
+ * + CastService
* - SSDPDiscoveryProvider
- * + DIALService
- * + DLNAService (limited to LG TVs, currently)
- * + NetcastTVService
- * + RokuService
- * + WebOSTVService
- * + MultiScreenService
+ * + DIALService
+ * + DLNAService (limited to LG TVs, currently)
+ * + NetcastTVService
+ * + RokuService
+ * + WebOSTVService
+ * + MultiScreenService
* - ZeroconfDiscoveryProvider
- * + AirPlayService
+ * + AirPlayService
*/
@SuppressWarnings("unchecked")
public void registerDefaultDeviceTypes() {
- final HashMap devicesList = DefaultPlatform.getDeviceServiceMap();
-
- for (HashMap.Entry entry : devicesList.entrySet()) {
+ final HashMap devicesList = new HashMap();
+ devicesList.put("com.connectsdk.service.WebOSTVService",
+ "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
+ //devicesList.put("com.connectsdk.service.NetcastTVService",
+ // "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
+ //devicesList.put("com.connectsdk.service.DLNAService",
+ // "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
+ //devicesList.put("com.connectsdk.service.DIALService",
+ // "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
+ // devicesList.put("com.connectsdk.service.RokuService",
+ // "com.connectsdk.discovery.provider.SSDPDiscoveryProvider");
+ // devicesList.put("com.connectsdk.service.CastService",
+ // "com.connectsdk.discovery.provider.CastDiscoveryProvider");
+ // devicesList.put("com.connectsdk.service.AirPlayService",
+ // "com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider");
+ // devicesList.put("com.connectsdk.service.FireTVService",
+ // "com.connectsdk.discovery.provider.FireTVDiscoveryProvider");
+
+ for (Map.Entry entry : devicesList.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
- try {
- registerDeviceService((Class) Class.forName(key), (Class)Class.forName(value));
+ try {
+ registerDeviceService((Class) Class.forName(key),
+ (Class) Class.forName(value));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
@@ -378,17 +407,22 @@ public void registerDefaultDeviceTypes() {
}
/**
- * Registers a DeviceService with DiscoveryManager and tells it which DiscoveryProvider to use to find it. Each DeviceService has a JSONObject of discovery parameters that its DiscoveryProvider will use to find it.
+ * Registers a DeviceService with DiscoveryManager and tells it which DiscoveryProvider to use to find it. Each
+ * DeviceService has a JSONObject of discovery parameters that its DiscoveryProvider will use to find it.
*
* @param deviceClass Class for object that should be instantiated when DeviceService is found
- * @param discoveryClass Class for object that should discover this DeviceService. If a DiscoveryProvider of this class already exists, then the existing DiscoveryProvider will be used.
+ * @param discoveryClass Class for object that should discover this DeviceService. If a DiscoveryProvider of this
+ * class already exists, then the existing DiscoveryProvider will be used.
*/
- public void registerDeviceService(Class extends DeviceService> deviceClass, Class extends DiscoveryProvider> discoveryClass) {
- if (!DeviceService.class.isAssignableFrom(deviceClass))
+ public void registerDeviceService(Class extends DeviceService> deviceClass,
+ Class extends DiscoveryProvider> discoveryClass) {
+ if (!DeviceService.class.isAssignableFrom(deviceClass)) {
return;
+ }
- if (!DiscoveryProvider.class.isAssignableFrom(discoveryClass))
+ if (!DiscoveryProvider.class.isAssignableFrom(discoveryClass)) {
return;
+ }
try {
DiscoveryProvider discoveryProvider = null;
@@ -416,8 +450,8 @@ public void registerDeviceService(Class extends DeviceService> deviceClass, Cl
deviceClasses.put(serviceId, deviceClass);
discoveryProvider.addDeviceFilter(discoveryFilter);
- if (mSearching){
- discoveryProvider.restart();
+ if (mSearching) {
+ discoveryProvider.restart();
}
} catch (SecurityException e) {
e.printStackTrace();
@@ -437,7 +471,8 @@ public void registerDeviceService(Class extends DeviceService> deviceClass, Cl
}
/**
- * Unregisters a DeviceService with DiscoveryManager. If no other DeviceServices are set to being discovered with the associated DiscoveryProvider, then that DiscoveryProvider instance will be stopped and shut down.
+ * Unregisters a DeviceService with DiscoveryManager. If no other DeviceServices are set to being discovered with
+ * the associated DiscoveryProvider, then that DiscoveryProvider instance will be stopped and shut down.
*
* @param deviceClass Class for DeviceService that should no longer be discovered
* @param discoveryClass Class for DiscoveryProvider that is discovering DeviceServices of deviceClass type
@@ -454,15 +489,16 @@ public void unregisterDeviceService(Class> deviceClass, Class> discoveryClas
try {
DiscoveryProvider discoveryProvider = null;
- for (DiscoveryProvider dp: discoveryProviders) {
+ for (DiscoveryProvider dp : discoveryProviders) {
if (dp.getClass().isAssignableFrom(discoveryClass)) {
discoveryProvider = dp;
break;
}
}
- if (discoveryProvider == null)
+ if (discoveryProvider == null) {
return;
+ }
Method m = deviceClass.getMethod("discoveryFilter");
Object result = m.invoke(null);
@@ -498,15 +534,16 @@ public void unregisterDeviceService(Class> deviceClass, Class> discoveryClas
* Start scanning for devices on the local network.
*/
public void start() {
- if (mSearching)
+ if (mSearching) {
return;
+ }
if (discoveryProviders == null) {
return;
}
mSearching = true;
- multicastLock.acquire();
+// multicastLock.acquire();
Util.runOnUI(new Runnable() {
@@ -516,25 +553,28 @@ public void run() {
registerDefaultDeviceTypes();
}
- ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-
- if (mWifi.isConnected()) {
+// ConnectivityManager connManager = (ConnectivityManager) context
+// .getSystemService(Context.CONNECTIVITY_SERVICE);
+// NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+//
+// if (mWifi.isConnected()) {
for (DiscoveryProvider provider : discoveryProviders) {
provider.start();
}
- } else {
- Log.w(Util.T, "Wifi is not connected yet");
-
- Util.runOnUI(new Runnable() {
-
- @Override
- public void run() {
- for (DiscoveryManagerListener listener : discoveryListeners)
- listener.onDiscoveryFailed(DiscoveryManager.this, new ServiceCommandError(0, "No wifi connection", null));
- }
- });
- }
+// } else {
+// Log.w(Util.T, "Wifi is not connected yet");
+//
+// Util.runOnUI(new Runnable() {
+//
+// @Override
+// public void run() {
+// for (DiscoveryManagerListener listener : discoveryListeners) {
+// listener.onDiscoveryFailed(DiscoveryManager.this,
+// new ServiceCommandError(0, "No wifi connection", null));
+// }
+// }
+// });
+// }
}
});
}
@@ -543,8 +583,9 @@ public void run() {
* Stop scanning for devices.
*/
public void stop() {
- if (!mSearching)
+ if (!mSearching) {
return;
+ }
mSearching = false;
@@ -552,32 +593,41 @@ public void stop() {
provider.stop();
}
- if (multicastLock.isHeld()) {
- multicastLock.release();
- }
+// if (multicastLock.isHeld()) {
+// multicastLock.release();
+// }
}
/**
- * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store.
+ * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation,
+ * DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided.
*
- * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided.
+ * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the
+ * ConnectableDeviceStore removeAll method.
*
- * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method.
+ * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the
+ * time of instantiation with `DiscoveryManager.init(context, null);`.
+ *
+ * @param connectableDeviceStore ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL
+ * certificates, recent access times, etc are kept in the device store.
*
- * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `DiscoveryManager.init(context, null);`.
*/
public void setConnectableDeviceStore(ConnectableDeviceStore connectableDeviceStore) {
this.connectableDeviceStore = connectableDeviceStore;
}
/**
- * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store.
+ * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation,
+ * DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided.
*
- * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided.
+ * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the
+ * ConnectableDeviceStore removeAll method.
*
- * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method.
- *
- * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `DiscoveryManager.init(context, null);`.
+ * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the
+ * time of instantiation with `DiscoveryManager.init(context, null);`.
+ *
+ * @return ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL
+ * certificates, recent access times, etc are kept in the device store.
*/
public ConnectableDeviceStore getConnectableDeviceStore() {
return connectableDeviceStore;
@@ -585,12 +635,13 @@ public ConnectableDeviceStore getConnectableDeviceStore() {
// @cond INTERNAL
public void handleDeviceAdd(ConnectableDevice device) {
- if (!deviceIsCompatible(device))
+ if (!deviceIsCompatible(device)) {
return;
+ }
compatibleDevices.put(device.getIpAddress(), device);
- for (DiscoveryManagerListener listenter: discoveryListeners) {
+ for (DiscoveryManagerListener listenter : discoveryListeners) {
listenter.onDeviceAdded(this, device);
}
}
@@ -598,22 +649,20 @@ public void handleDeviceAdd(ConnectableDevice device) {
public void handleDeviceUpdate(ConnectableDevice device) {
if (deviceIsCompatible(device)) {
if (device.getIpAddress() != null && compatibleDevices.containsKey(device.getIpAddress())) {
- for (DiscoveryManagerListener listenter: discoveryListeners) {
+ for (DiscoveryManagerListener listenter : discoveryListeners) {
listenter.onDeviceUpdated(this, device);
}
- }
- else {
+ } else {
handleDeviceAdd(device);
}
- }
- else {
+ } else {
compatibleDevices.remove(device.getIpAddress());
handleDeviceLoss(device);
}
}
public void handleDeviceLoss(ConnectableDevice device) {
- for (DiscoveryManagerListener listenter: discoveryListeners) {
+ for (DiscoveryManagerListener listenter : discoveryListeners) {
listenter.onDeviceRemoved(this, device);
}
@@ -640,36 +689,49 @@ public boolean isNetcast(ServiceDescription description) {
// @endcond
/**
- * List of all devices discovered by DiscoveryManager. Each ConnectableDevice object is keyed against its current IP address.
+ * @return List of all devices discovered by DiscoveryManager. Each ConnectableDevice object is keyed against its current IP
+ * address.
*/
public Map getAllDevices() {
return allDevices;
}
/**
- * Filtered list of discovered ConnectableDevices, limited to devices that match at least one of the CapabilityFilters in the capabilityFilters array. Each ConnectableDevice object is keyed against its current IP address.
+ * @return Filtered list of discovered ConnectableDevices, limited to devices that match at least one of the
+ * CapabilityFilters in the capabilityFilters array. Each ConnectableDevice object is keyed against its current IP
+ * address.
*/
public Map getCompatibleDevices() {
return compatibleDevices;
}
/**
- * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available.
+ * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be
+ * available.
*
- * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice.
+ * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt
+ * the user to pair when connecting to the ConnectableDevice.
*
- * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available.
+ * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid
+ * requiring pairing if possible but some capabilities may not be available.
+ *
+ * @return the pairing level
*/
public PairingLevel getPairingLevel() {
return pairingLevel;
}
/**
- * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available.
+ * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be
+ * available.
*
- * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice.
+ * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt
+ * the user to pair when connecting to the ConnectableDevice.
*
- * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available.
+ * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid
+ * requiring pairing if possible but some capabilities may not be available.
+ *
+ * @param pairingLevel the pairing level
*/
public void setPairingLevel(PairingLevel pairingLevel) {
this.pairingLevel = pairingLevel;
@@ -681,7 +743,7 @@ public Context getContext() {
}
public void onDestroy() {
- unregisterBroadcastReceiver();
+ //unregisterBroadcastReceiver();
}
public List getDiscoveryProviders() {
@@ -705,14 +767,26 @@ public void onCapabilityUpdated(ConnectableDevice device, List added, Li
handleDeviceUpdate(device);
}
- @Override public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) { }
- @Override public void onDeviceDisconnected(ConnectableDevice device) { }
- @Override public void onDeviceReady(ConnectableDevice device) { }
- @Override public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) { }
+ @Override
+ public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) {
+ }
+
+ @Override
+ public void onDeviceDisconnected(ConnectableDevice device) {
+ }
+
+ @Override
+ public void onDeviceReady(ConnectableDevice device) {
+ }
+
+ @Override
+ public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) {
+ }
@Override
public void onServiceAdded(DiscoveryProvider provider, ServiceDescription serviceDescription) {
- Log.d(Util.T, "Service added: " + serviceDescription.getFriendlyName() + " (" + serviceDescription.getServiceID() + ")");
+ Log.d(Util.T, "Service added: " + serviceDescription.getFriendlyName() + " ("
+ + serviceDescription.getServiceID() + ")");
boolean deviceIsNew = !allDevices.containsKey(serviceDescription.getIpAddress());
ConnectableDevice device = null;
@@ -740,8 +814,8 @@ public void onServiceAdded(DiscoveryProvider provider, ServiceDescription servic
device.setFriendlyName(serviceDescription.getFriendlyName());
device.setLastDetection(Util.getTime());
device.setLastKnownIPAddress(serviceDescription.getIpAddress());
- // TODO: Implement the currentSSID Property in DiscoveryManager
-// device.setLastSeenOnWifi(currentSSID);
+ // TODO: Implement the currentSSID Property in DiscoveryManager
+ // device.setLastSeenOnWifi(currentSSID);
addServiceDescriptionToDevice(serviceDescription, device);
@@ -753,11 +827,12 @@ public void onServiceAdded(DiscoveryProvider provider, ServiceDescription servic
return;
}
- if (deviceIsNew)
+ if (deviceIsNew) {
handleDeviceAdd(device);
- else
+ } else {
handleDeviceUpdate(device);
- }
+ }
+ }
@Override
public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serviceDescription) {
@@ -771,15 +846,14 @@ public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serv
ConnectableDevice device = allDevices.get(serviceDescription.getIpAddress());
- if (device != null) {
+ if (device != null) {
device.removeServiceWithId(serviceDescription.getServiceID());
if (device.getServices().isEmpty()) {
allDevices.remove(serviceDescription.getIpAddress());
handleDeviceLoss(device);
- }
- else {
+ } else {
handleDeviceUpdate(device);
}
}
@@ -788,32 +862,38 @@ public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serv
@Override
public void onServiceDiscoveryFailed(DiscoveryProvider provider, ServiceCommandError error) {
Log.w(Util.T, "DiscoveryProviderListener, Service Discovery Failed");
- }
+ }
@SuppressWarnings("unchecked")
public void addServiceDescriptionToDevice(ServiceDescription desc, ConnectableDevice device) {
- Log.d(Util.T, "Adding service " + desc.getServiceID() + " to device with address " + device.getIpAddress() + " and id " + device.getId());
+ Log.d(Util.T, "Adding service " + desc.getServiceID() + " to device with address " + device.getIpAddress()
+ + " and id " + device.getId());
Class extends DeviceService> deviceServiceClass = deviceClasses.get(desc.getServiceID());
- if (deviceServiceClass == null)
+ if (deviceServiceClass == null) {
return;
+ }
if (deviceServiceClass == DLNAService.class) {
- if (desc.getLocationXML() == null)
+ if (desc.getLocationXML() == null) {
return;
+ }
} else if (deviceServiceClass == NetcastTVService.class) {
- if (!isNetcast(desc))
+ if (!isNetcast(desc)) {
return;
- }
+ }
+ }
ServiceConfig serviceConfig = null;
- if (connectableDeviceStore != null)
+ if (connectableDeviceStore != null) {
serviceConfig = connectableDeviceStore.getServiceConfig(desc);
+ }
- if (serviceConfig == null)
+ if (serviceConfig == null) {
serviceConfig = new ServiceConfig(desc);
+ }
serviceConfig.setListener(DiscoveryManager.this);
@@ -836,8 +916,9 @@ public void addServiceDescriptionToDevice(ServiceDescription desc, ConnectableDe
DeviceService alreadyAddedService = device.getServiceByName(desc.getServiceID());
- if (alreadyAddedService != null)
+ if (alreadyAddedService != null) {
alreadyAddedService.setServiceDescription(desc);
+ }
return;
}
diff --git a/src/com/connectsdk/discovery/DiscoveryProvider.java b/src/com/connectsdk/discovery/DiscoveryProvider.java
index 99aa4fc0..63f8ed2a 100644
--- a/src/com/connectsdk/discovery/DiscoveryProvider.java
+++ b/src/com/connectsdk/discovery/DiscoveryProvider.java
@@ -20,8 +20,6 @@
package com.connectsdk.discovery;
-import java.util.List;
-
/**
* ###Overview
@@ -64,10 +62,12 @@ public interface DiscoveryProvider {
*/
public void reset();
- /** Adds a DiscoveryProviderListener, which should be the DiscoveryManager */
+ /** Adds a DiscoveryProviderListener, which should be the DiscoveryManager
+ * @param listener the listener */
public void addListener(DiscoveryProviderListener listener);
- /** Removes a DiscoveryProviderListener. */
+ /** Removes a DiscoveryProviderListener.
+ * @param listener the listener */
public void removeListener(DiscoveryProviderListener listener);
/**
@@ -85,14 +85,7 @@ public interface DiscoveryProvider {
public void removeDeviceFilter(DiscoveryFilter filter);
/**
- * Set filters for a list of particular DeviceServices
- *
- * @param filters filters to be used for discovering a list of particular DeviceServices
- */
- public void setFilters(List filters);
-
- /**
- * Whether or not the DiscoveryProvider has any services it is supposed to be searching for. If YES, then the DiscoveryProvider will be stopped and de-referenced by the DiscoveryManager.
+ * @return true if the DiscoveryProvider has any services it is supposed to be searching for. If YES, then the DiscoveryProvider will be stopped and de-referenced by the DiscoveryManager.
*/
public boolean isEmpty();
}
diff --git a/src/com/connectsdk/discovery/DiscoveryProviderListener.java b/src/com/connectsdk/discovery/DiscoveryProviderListener.java
index 4e51e46b..c0434cbd 100644
--- a/src/com/connectsdk/discovery/DiscoveryProviderListener.java
+++ b/src/com/connectsdk/discovery/DiscoveryProviderListener.java
@@ -32,7 +32,7 @@ public interface DiscoveryProviderListener {
* This method is called when the DiscoveryProvider discovers a service that matches one of its DeviceService filters. The ServiceDescription is created and passed to the listener (which should be the DiscoveryManager). The ServiceDescription is used to create a DeviceService, which is then attached to a ConnectableDevice object.
*
* @param provider DiscoveryProvider that found the service
- * @param description ServiceDescription of the service that was found
+ * @param serviceDescription ServiceDescription of the service that was found
*/
public void onServiceAdded(DiscoveryProvider provider, ServiceDescription serviceDescription);
@@ -40,7 +40,7 @@ public interface DiscoveryProviderListener {
* This method is called when the DiscoveryProvider's internal mechanism loses reference to a service that matches one of its DeviceService filters.
*
* @param provider DiscoveryProvider that lost the service
- * @param description ServiceDescription of the service that was lost
+ * @param serviceDescription ServiceDescription of the service that was lost
*/
public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serviceDescription);
diff --git a/src/com/connectsdk/discovery/provider/SSDPDiscoveryProvider.java b/src/com/connectsdk/discovery/provider/SSDPDiscoveryProvider.java
index dfc14abe..0cac0bff 100644
--- a/src/com/connectsdk/discovery/provider/SSDPDiscoveryProvider.java
+++ b/src/com/connectsdk/discovery/provider/SSDPDiscoveryProvider.java
@@ -20,24 +20,9 @@
package com.connectsdk.discovery.provider;
-import android.content.Context;
-import android.util.Log;
-
-import com.connectsdk.core.Util;
-import com.connectsdk.discovery.DiscoveryFilter;
-import com.connectsdk.discovery.DiscoveryProvider;
-import com.connectsdk.discovery.DiscoveryProviderListener;
-import com.connectsdk.discovery.provider.ssdp.SSDPClient;
-import com.connectsdk.discovery.provider.ssdp.SSDPDevice;
-import com.connectsdk.discovery.provider.ssdp.SSDPPacket;
-import com.connectsdk.service.config.ServiceDescription;
-
-import org.xml.sax.SAXException;
-
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
-import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -45,55 +30,64 @@
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
-public class SSDPDiscoveryProvider implements DiscoveryProvider {
- Context context;
+import org.xml.sax.SAXException;
+
+import com.connectsdk.core.Context;
+import com.connectsdk.core.Log;
+import com.connectsdk.core.Util;
+import com.connectsdk.discovery.DiscoveryFilter;
+import com.connectsdk.discovery.DiscoveryProvider;
+import com.connectsdk.discovery.DiscoveryProviderListener;
+import com.connectsdk.discovery.provider.ssdp.SSDPClient;
+import com.connectsdk.discovery.provider.ssdp.SSDPDevice;
+import com.connectsdk.discovery.provider.ssdp.SSDPPacket;
+import com.connectsdk.service.config.ServiceDescription;
- boolean needToStartSearch = false;
+public class SSDPDiscoveryProvider implements DiscoveryProvider {
+ private Context context;
- private CopyOnWriteArrayList serviceListeners;
+ private CopyOnWriteArrayList serviceListeners = new CopyOnWriteArrayList();
- ConcurrentHashMap foundServices = new ConcurrentHashMap();
- ConcurrentHashMap discoveredServices = new ConcurrentHashMap();
+ private ConcurrentHashMap foundServices = new ConcurrentHashMap();
+ private ConcurrentHashMap discoveredServices = new ConcurrentHashMap();
- List serviceFilters;
+ private List serviceFilters = new CopyOnWriteArrayList();
private SSDPClient ssdpClient;
private Timer scanTimer;
- private Pattern uuidReg;
+ private Pattern uuidReg = Pattern.compile("(?<=uuid:)(.+?)(?=(::)|$)");
private Thread responseThread;
private Thread notifyThread;
-
- boolean isRunning = false;
+ private ScheduledExecutorService executorService;
+ private boolean isRunning = false;
public SSDPDiscoveryProvider(Context context) {
this.context = context;
-
- uuidReg = Pattern.compile("(?<=uuid:)(.+?)(?=(::)|$)");
-
- serviceListeners = new CopyOnWriteArrayList();
- serviceFilters = new CopyOnWriteArrayList();
}
private void openSocket() {
- if (ssdpClient != null && ssdpClient.isConnected())
+ if (ssdpClient != null && ssdpClient.isConnected()) {
return;
+ }
try {
- InetAddress source = Util.getIpAddress(context);
- if (source == null)
+ InetAddress source = context.getIpAddress();
+ if (source == null) {
return;
+ }
ssdpClient = createSocket(source);
- } catch (UnknownHostException e) {
- e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
@@ -105,13 +99,18 @@ protected SSDPClient createSocket(InetAddress source) throws IOException {
@Override
public void start() {
- if (isRunning)
+ if (isRunning) {
return;
+ }
isRunning = true;
openSocket();
-
+ if (!serviceFilters.isEmpty()) {
+ // three tasks for each service filter
+ int poolSize = serviceFilters.size() * 3;
+ executorService = Executors.newScheduledThreadPool(poolSize);
+ }
scanTimer = new Timer();
scanTimer.schedule(new TimerTask() {
@@ -121,8 +120,8 @@ public void run() {
}
}, 100, RESCAN_INTERVAL);
- responseThread = new Thread(mResponseHandler);
- notifyThread = new Thread(mRespNotifyHandler);
+ responseThread = new Thread(mResponseHandler, "Connect SDK Response");
+ notifyThread = new Thread(mRespNotifyHandler, "Connect SDK Notify");
responseThread.start();
notifyThread.start();
@@ -147,8 +146,9 @@ public void sendSearch() {
notifyListenersOfLostService(service);
}
- if (foundServices.containsKey(key))
+ if (foundServices.containsKey(key)) {
foundServices.remove(key);
+ }
}
rescan();
@@ -177,6 +177,10 @@ public void stop() {
ssdpClient.close();
ssdpClient = null;
}
+
+ if (executorService != null && !executorService.isShutdown()) {
+ executorService.shutdown();
+ }
}
@Override
@@ -194,26 +198,31 @@ public void reset() {
@Override
public void rescan() {
- for (DiscoveryFilter searchTarget : serviceFilters) {
- final String message = SSDPClient.getSSDPSearchMessage(searchTarget.getServiceFilter());
-
- Timer timer = new Timer();
- /* Send 3 times like WindowsMedia */
- for (int i = 0; i < 3; i++) {
- TimerTask task = new TimerTask() {
-
- @Override
- public void run() {
- try {
- if (ssdpClient != null)
- ssdpClient.send(message);
- } catch (IOException e) {
- e.printStackTrace();
+ if (executorService == null || executorService.isShutdown()) {
+ Log.w(Util.T, "There are no filters added");
+ } else {
+ if (executorService.isTerminated() || executorService.isShutdown()) {
+ if (!serviceFilters.isEmpty()) {
+ int poolSize = serviceFilters.size() * 3;
+ executorService = Executors.newScheduledThreadPool(poolSize);
+ }
+ }
+ for (DiscoveryFilter filter : serviceFilters) {
+ final String message = SSDPClient.getSSDPSearchMessage(filter.getServiceFilter());
+ /* Send 3 times like WindowsMedia */
+ for (int i = 0; i < 3; i++) {
+ executorService.schedule(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if (ssdpClient != null)
+ ssdpClient.send(message);
+ } catch (IOException ex) {
+ Log.e(Util.T, ex.getMessage());
+ }
}
- }
- };
-
- timer.schedule(task, i * 1000);
+ }, i, TimeUnit.SECONDS);
+ }
}
}
@@ -233,11 +242,6 @@ public void removeDeviceFilter(DiscoveryFilter filter) {
serviceFilters.remove(filter);
}
- @Override
- public void setFilters(List filters) {
- serviceFilters = filters;
- }
-
@Override
public boolean isEmpty() {
return serviceFilters.size() == 0;
@@ -250,6 +254,9 @@ public void run() {
try {
handleSSDPPacket(new SSDPPacket(ssdpClient.responseReceive()));
} catch (IOException e) {
+ if ("Socket closed".equals(e.getMessage())) { // expected during shutdown
+ break;
+ }
e.printStackTrace();
break;
} catch (RuntimeException e) {
@@ -267,6 +274,9 @@ public void run() {
try {
handleSSDPPacket(new SSDPPacket(ssdpClient.multicastReceive()));
} catch (IOException e) {
+ if ("Socket closed".equals(e.getMessage())) { // expected during shutdown
+ break;
+ }
e.printStackTrace();
break;
} catch (RuntimeException e) {
@@ -279,37 +289,43 @@ public void run() {
private void handleSSDPPacket(SSDPPacket ssdpPacket) {
// Debugging stuff
-// Util.runOnUI(new Runnable() {
-//
-// @Override
-// public void run() {
-// Log.d("Connect SDK Socket", "Packet received | type = " + ssdpPacket.type);
-//
-// for (String key : ssdpPacket.data.keySet()) {
-// Log.d("Connect SDK Socket", " " + key + " = " + ssdpPacket.data.get(key));
-// }
-// Log.d("Connect SDK Socket", "__________________________________________");
-// }
-// });
+ // Util.runOnUI(new Runnable() {
+ //
+ // @Override
+ // public void run() {
+ // Log.d("Connect SDK Socket", "Packet received | type = " + ssdpPacket.getType() + " data = " +
+ // ssdpPacket.getData());
+ //
+ // for (String key : ssdpPacket.getData().keySet()) {
+ // Log.d("Connect SDK Socket", " " + key + " = " + ssdpPacket.getData().get(key));
+ // }
+ // Log.d("Connect SDK Socket", "__________________________________________");
+ // }
+ // });
// End Debugging stuff
- if (ssdpPacket == null || ssdpPacket.getData().size() == 0 || ssdpPacket.getType() == null)
+ if (ssdpPacket == null || ssdpPacket.getData().size() == 0 || ssdpPacket.getType() == null) {
return;
+ }
String serviceFilter = ssdpPacket.getData().get(ssdpPacket.getType().equals(SSDPClient.NOTIFY) ? "NT" : "ST");
- if (serviceFilter == null || SSDPClient.MSEARCH.equals(ssdpPacket.getType()) || !isSearchingForFilter(serviceFilter))
+ if (serviceFilter == null || SSDPClient.MSEARCH.equals(ssdpPacket.getType())
+ || !isSearchingForFilter(serviceFilter)) {
return;
+ }
String usnKey = ssdpPacket.getData().get("USN");
- if (usnKey == null || usnKey.length() == 0)
+ if (usnKey == null || usnKey.length() == 0) {
return;
+ }
Matcher m = uuidReg.matcher(usnKey);
- if (!m.find())
+ if (!m.find()) {
return;
+ }
String uuid = m.group();
@@ -324,8 +340,9 @@ private void handleSSDPPacket(SSDPPacket ssdpPacket) {
} else {
String location = ssdpPacket.getData().get("LOCATION");
- if (location == null || location.length() == 0)
+ if (location == null || location.length() == 0) {
return;
+ }
ServiceDescription foundService = foundServices.get(uuid);
ServiceDescription discoverdService = discoveredServices.get(uuid);
@@ -344,8 +361,9 @@ private void handleSSDPPacket(SSDPPacket ssdpPacket) {
getLocationData(location, uuid, serviceFilter);
}
- if (foundService != null)
+ if (foundService != null) {
foundService.setLastDetection(new Date().getTime());
+ }
}
}
@@ -375,30 +393,28 @@ public void run() {
if (device != null) {
device.UUID = uuid;
- boolean hasServices = containsServicesWithFilter(device, serviceFilter);
-
- if (hasServices) {
- final ServiceDescription service = discoveredServices.get(uuid);
-
- if (service != null) {
- service.setServiceFilter(serviceFilter);
- service.setFriendlyName(device.friendlyName);
- service.setModelName(device.modelName);
- service.setModelNumber(device.modelNumber);
- service.setModelDescription(device.modelDescription);
- service.setManufacturer(device.manufacturer);
- service.setApplicationURL(device.applicationURL);
- service.setServiceList(device.serviceList);
- service.setResponseHeaders(device.headers);
- service.setLocationXML(device.locationXML);
- service.setServiceURI(device.serviceURI);
- service.setPort(device.port);
-
- foundServices.put(uuid, service);
-
- notifyListenersOfNewService(service);
- }
+
+ final ServiceDescription service = discoveredServices.get(uuid);
+
+ if (service != null) {
+ service.setServiceFilter(serviceFilter);
+ service.setFriendlyName(device.friendlyName);
+ service.setModelName(device.modelName);
+ service.setModelNumber(device.modelNumber);
+ service.setModelDescription(device.modelDescription);
+ service.setManufacturer(device.manufacturer);
+ service.setApplicationURL(device.applicationURL);
+ service.setServiceList(device.serviceList);
+ service.setResponseHeaders(device.headers);
+ service.setLocationXML(device.locationXML);
+ service.setServiceURI(device.serviceURI);
+ service.setPort(device.port);
+
+ foundServices.put(uuid, service);
+
+ notifyListenersOfNewService(service);
}
+
}
discoveredServices.remove(uuid);
@@ -459,8 +475,9 @@ public List serviceIdsForFilter(String filter) {
if (ssdpFilter.equals(filter)) {
String serviceId = serviceFilter.getServiceId();
- if (serviceId != null)
+ if (serviceId != null) {
serviceIds.add(serviceId);
+ }
}
}
@@ -471,24 +488,14 @@ public boolean isSearchingForFilter(String filter) {
for (DiscoveryFilter serviceFilter : serviceFilters) {
String ssdpFilter = serviceFilter.getServiceFilter();
- if (ssdpFilter.equals(filter))
+ if (ssdpFilter.equals(filter)) {
return true;
+ }
}
return false;
}
- public boolean containsServicesWithFilter(SSDPDevice device, String filter) {
-// List servicesRequired = new ArrayList();
-//
-// for (JSONObject serviceFilter : serviceFilters) {
-// }
-
- // TODO Implement this method. Not sure why needs to happen since there are now required services.
-
- return true;
- }
-
@Override
public void addListener(DiscoveryProviderListener listener) {
serviceListeners.add(listener);
diff --git a/src/com/connectsdk/discovery/provider/ZeroconfDiscoveryProvider.java b/src/com/connectsdk/discovery/provider/ZeroconfDiscoveryProvider.java
index a72381fc..9c287408 100644
--- a/src/com/connectsdk/discovery/provider/ZeroconfDiscoveryProvider.java
+++ b/src/com/connectsdk/discovery/provider/ZeroconfDiscoveryProvider.java
@@ -20,9 +20,16 @@
package com.connectsdk.discovery.provider;
+import com.connectsdk.core.Context;
+import com.connectsdk.core.Log;
+import com.connectsdk.core.Util;
+import com.connectsdk.discovery.DiscoveryFilter;
+import com.connectsdk.discovery.DiscoveryProvider;
+import com.connectsdk.discovery.DiscoveryProviderListener;
+import com.connectsdk.service.config.ServiceDescription;
+
import java.io.IOException;
import java.net.InetAddress;
-import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -35,15 +42,6 @@
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
-import android.content.Context;
-import android.util.Log;
-
-import com.connectsdk.core.Util;
-import com.connectsdk.discovery.DiscoveryFilter;
-import com.connectsdk.discovery.DiscoveryProvider;
-import com.connectsdk.discovery.DiscoveryProviderListener;
-import com.connectsdk.service.config.ServiceDescription;
-
public class ZeroconfDiscoveryProvider implements DiscoveryProvider {
private static final String HOSTNAME = "connectsdk";
@@ -52,10 +50,11 @@ public class ZeroconfDiscoveryProvider implements DiscoveryProvider {
private Timer scanTimer;
- List serviceFilters;
+ private List serviceFilters = new CopyOnWriteArrayList();
- ConcurrentHashMap foundServices;
- CopyOnWriteArrayList serviceListeners;
+ private ConcurrentHashMap foundServices = new ConcurrentHashMap(8, 0.75f, 2);
+ private CopyOnWriteArrayList serviceListeners = new CopyOnWriteArrayList();
+
boolean isRunning = false;
@@ -75,10 +74,9 @@ public void serviceResolved(ServiceEvent ev) {
ServiceDescription foundService = foundServices.get(ipAddress);
- boolean isNew = foundService == null;
boolean listUpdateFlag = false;
- if (isNew) {
+ if (foundService == null) { // is New
foundService = new ServiceDescription();
foundService.setUUID(ipAddress);
foundService.setServiceFilter(ev.getInfo().getType());
@@ -88,8 +86,7 @@ public void serviceResolved(ServiceEvent ev) {
foundService.setFriendlyName(friendlyName);
listUpdateFlag = true;
- }
- else {
+ } else {
if (!foundService.getFriendlyName().equals(friendlyName)) {
foundService.setFriendlyName(friendlyName);
listUpdateFlag = true;
@@ -136,16 +133,7 @@ public void serviceAdded(ServiceEvent event) {
};
public ZeroconfDiscoveryProvider(Context context) {
- foundServices = new ConcurrentHashMap(8, 0.75f, 2);
-
- serviceListeners = new CopyOnWriteArrayList();
- serviceFilters = new CopyOnWriteArrayList();
-
- try {
- srcAddress = Util.getIpAddress(context);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
+ srcAddress = context.getIpAddress();
}
@Override
@@ -216,7 +204,9 @@ public void stop() {
if (jmdns != null) {
for (DiscoveryFilter searchTarget : serviceFilters) {
String filter = searchTarget.getServiceFilter();
- jmdns.removeServiceListener(filter, jmdnsListener);
+ if (filter != null && !filter.isEmpty()) {
+ jmdns.removeServiceListener(filter, jmdnsListener);
+ }
}
}
}
@@ -245,7 +235,9 @@ public void rescan() {
if (jmdns != null) {
for (DiscoveryFilter searchTarget : serviceFilters) {
String filter = searchTarget.getServiceFilter();
- jmdns.addServiceListener(filter, jmdnsListener);
+ if (filter != null && !filter.isEmpty()) {
+ jmdns.addServiceListener(filter, jmdnsListener);
+ }
}
}
} catch (IOException e) {
@@ -277,10 +269,6 @@ public void removeDeviceFilter(DiscoveryFilter filter) {
serviceFilters.remove(filter);
}
- @Override
- public void setFilters(List filters) {
- serviceFilters = filters;
- }
@Override
public boolean isEmpty() {
diff --git a/src/com/connectsdk/discovery/provider/ssdp/Action.java b/src/com/connectsdk/discovery/provider/ssdp/Action.java
deleted file mode 100644
index ce87cfae..00000000
--- a/src/com/connectsdk/discovery/provider/ssdp/Action.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Action
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Copyright (c) 2011 stonker.lee@gmail.com https://code.google.com/p/android-dlna/
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.discovery.provider.ssdp;
-
-import java.util.List;
-
-
-public class Action {
- /* Required. Name of action. */
- String mName;
-
- /* Required. */
- List mArgumentList;
-
- public Action(String name) {
- this.mName = name;
- }
-}
\ No newline at end of file
diff --git a/src/com/connectsdk/discovery/provider/ssdp/Argument.java b/src/com/connectsdk/discovery/provider/ssdp/Argument.java
deleted file mode 100644
index 4f6b9608..00000000
--- a/src/com/connectsdk/discovery/provider/ssdp/Argument.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Argument
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Copyright (c) 2011 stonker.lee@gmail.com https://code.google.com/p/android-dlna/
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.discovery.provider.ssdp;
-
-public class Argument {
- public static final String TAG = "argument";
- public static final String TAG_NAME = "name";
- public static final String TAG_DIRECTION = "direction";
- public static final String TAG_RETVAL = "retval";
- public static final String TAG_RELATED_STATE_VARIABLE = "relatedStateVariable";
-
- /* Required. Name of formal parameter. */
- String mName;
- /* Required. Defines whether argument is an input or output paramter. */
- String mDirection;
- /* Optional. Identifies at most one output argument as the return value. */
- String mRetval;
- /* Required. Must be the same of a state variable. */
- String mRelatedStateVariable;
-}
\ No newline at end of file
diff --git a/src/com/connectsdk/discovery/provider/ssdp/Icon.java b/src/com/connectsdk/discovery/provider/ssdp/Icon.java
index 923fa596..9058595d 100644
--- a/src/com/connectsdk/discovery/provider/ssdp/Icon.java
+++ b/src/com/connectsdk/discovery/provider/ssdp/Icon.java
@@ -2,20 +2,20 @@
public class Icon {
static final String TAG = "icon";
- static final String TAG_MIME_TYPE = "mimetype";
- static final String TAG_WIDTH = "width";
- static final String TAG_HEIGHT = "height";
- static final String TAG_DEPTH = "depth";
- static final String TAG_URL = "url";
+ //static final String TAG_MIME_TYPE = "mimetype";
+ //static final String TAG_WIDTH = "width";
+ //static final String TAG_HEIGHT = "height";
+ //static final String TAG_DEPTH = "depth";
+ //static final String TAG_URL = "url";
/* Required. Icon's MIME type. */
- String mimetype;
+ //String mimetype;
/* Required. Horizontal dimension of icon in pixels. */
- String width;
+ //String width;
/* Required. Vertical dimension of icon in pixels. */
- String height;
+ //String height;
/* Required. Number of color bits per pixel. */
- String depth;
+ //String depth;
/* Required. Pointer to icon image. */
- String url;
+ //String url;
}
diff --git a/src/com/connectsdk/discovery/provider/ssdp/SSDPClient.java b/src/com/connectsdk/discovery/provider/ssdp/SSDPClient.java
index 234e2528..7de3b022 100644
--- a/src/com/connectsdk/discovery/provider/ssdp/SSDPClient.java
+++ b/src/com/connectsdk/discovery/provider/ssdp/SSDPClient.java
@@ -1,10 +1,10 @@
/*
* SSDPClient
* Connect SDK
- *
+ *
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 6 Jan 2015
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -29,6 +29,7 @@
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.net.SocketException;
+import java.nio.charset.Charset;
public class SSDPClient {
/* New line definition */
@@ -62,7 +63,6 @@ public class SSDPClient {
SocketAddress multicastGroup;
NetworkInterface networkInterface;
InetAddress localInAddress;
-
int timeout = 0;
static int MX = 5;
@@ -83,15 +83,19 @@ public SSDPClient(InetAddress source, MulticastSocket mcSocket, DatagramSocket d
datagramSocket.bind(new InetSocketAddress(localInAddress, 0));
}
- /** Used to send SSDP packet */
+ /** Used to send SSDP packet.
+ * @param data the data
+ * @throws IOException in case of network problems */
public void send(String data) throws IOException {
- DatagramPacket dp = new DatagramPacket(data.getBytes(), data.length(), multicastGroup);
-
+ byte[] buffer = data.getBytes(Charset.forName("US-ASCII"));
+ DatagramPacket dp = new DatagramPacket(buffer, buffer.length, multicastGroup);
datagramSocket.send(dp);
}
- /** Used to receive SSDP Response packet */
+ /** Used to receive SSDP Response packet.
+ * @return response
+ * @throws IOException in case of network problems */
public DatagramPacket responseReceive() throws IOException {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
@@ -101,7 +105,9 @@ public DatagramPacket responseReceive() throws IOException {
return dp;
}
- /** Used to receive SSDP Multicast packet */
+ /** Used to receive SSDP Multicast packet.
+ * @return multicast packet
+ * @throws IOException in case of network problems */
public DatagramPacket multicastReceive() throws IOException {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
@@ -120,7 +126,7 @@ public boolean isConnected() {
return datagramSocket != null && multicastSocket != null && datagramSocket.isConnected() && multicastSocket.isConnected();
}
- /** Close the socket */
+ /** Close the socket. */
public void close() {
if (multicastSocket != null) {
try {
@@ -132,8 +138,7 @@ public void close() {
}
if (datagramSocket != null) {
- datagramSocket.disconnect();
- datagramSocket.close();
+ datagramSocket.close();
}
}
diff --git a/src/com/connectsdk/discovery/provider/ssdp/SSDPDevice.java b/src/com/connectsdk/discovery/provider/ssdp/SSDPDevice.java
index ddccba81..1cd3afa5 100644
--- a/src/com/connectsdk/discovery/provider/ssdp/SSDPDevice.java
+++ b/src/com/connectsdk/discovery/provider/ssdp/SSDPDevice.java
@@ -26,6 +26,7 @@
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -66,7 +67,7 @@ public class SSDPDevice {
/* Optional. */
public List serviceList = new ArrayList();
- public String ST;
+// public String ST;
public String applicationURL;
public String serviceURI;
@@ -99,7 +100,6 @@ public SSDPDevice(URL urlObject, String ST) throws IOException, ParserConfigurat
public void parse(URL url) throws IOException, ParserConfigurationException, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser;
SSDPDeviceDescriptionParser parser = new SSDPDeviceDescriptionParser(this);
@@ -111,18 +111,14 @@ public void parse(URL url) throws IOException, ParserConfigurationException, SAX
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
- Scanner s = null;
- try {
- s = new Scanner(in).useDelimiter("\\A");
+
+ try (Scanner s = new Scanner(in, "UTF-8")) {
+ s.useDelimiter("\\A");
locationXML = s.hasNext() ? s.next() : "";
- saxParser = factory.newSAXParser();
- saxParser.parse(new ByteArrayInputStream(locationXML.getBytes()), parser);
- } finally {
- in.close();
- if (s != null)
- s.close();
- }
+ SAXParser saxParser = factory.newSAXParser();
+ saxParser.parse(new ByteArrayInputStream(locationXML.getBytes(StandardCharsets.UTF_8)), parser);
+ }
headers = urlConnection.getHeaderFields();
}
diff --git a/src/com/connectsdk/discovery/provider/ssdp/Service.java b/src/com/connectsdk/discovery/provider/ssdp/Service.java
index 2bfa6cc0..86a7394d 100644
--- a/src/com/connectsdk/discovery/provider/ssdp/Service.java
+++ b/src/com/connectsdk/discovery/provider/ssdp/Service.java
@@ -20,7 +20,7 @@
package com.connectsdk.discovery.provider.ssdp;
-import java.util.List;
+
//import com.connectsdk.core.upnp.parser.Parser;
@@ -44,8 +44,8 @@ public class Service {
/* Relative. Relative URL for eventing. */
public String eventSubURL;
- public List actionList;
- public List serviceStateTable;
+
+ //public List serviceStateTable;
/*
* We don't get SCPD, control and eventSub descriptions at service creation.
diff --git a/src/com/connectsdk/discovery/provider/ssdp/StateVariable.java b/src/com/connectsdk/discovery/provider/ssdp/StateVariable.java
deleted file mode 100644
index 10b2ea5d..00000000
--- a/src/com/connectsdk/discovery/provider/ssdp/StateVariable.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * StateVariable
- * Connect SDK
- *
- * Copyright (c) 2014 LG Electronics.
- * Copyright (c) 2011 stonker.lee@gmail.com https://code.google.com/p/android-dlna/
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.connectsdk.discovery.provider.ssdp;
-
-public class StateVariable {
- public static final String TAG = "stateVariable";
- public static final String TAG_NAME = "name";
- public static final String TAG_DATA_TYPE = "dataType";
-
- /* Optional. Defines whether event messages will be generated when the value
- * of this state variable changes. Defaut value is "yes".
- */
- String mSendEvents = "yes";
-
- /* Optional. Defines whether event messages will be delivered using
- * multicast eventing. Default value is "no".
- */
- String mMulticast = "no";
-
- /* Required. Name of state variable. */
- String mName;
-
- /* Required. Same as data types defined by XML Schema. */
- String mDataType;
-
-}
\ No newline at end of file
diff --git a/src/com/connectsdk/etc/helper/HttpConnection.java b/src/com/connectsdk/etc/helper/HttpConnection.java
index d0b4d784..284bea63 100644
--- a/src/com/connectsdk/etc/helper/HttpConnection.java
+++ b/src/com/connectsdk/etc/helper/HttpConnection.java
@@ -29,6 +29,7 @@
import java.net.ProtocolException;
import java.net.Socket;
import java.net.URI;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -111,7 +112,7 @@ public void execute() throws IOException {
}
try {
BufferedReader reader =
- new BufferedReader(new InputStreamReader(connection.getInputStream()));
+ new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
StringBuilder sb = new StringBuilder();
while (null != (line = reader.readLine())) {
@@ -131,7 +132,7 @@ public void execute() throws IOException {
@Override
public void setPayload(String payload) {
- this.payload = payload.getBytes();
+ this.payload = payload.getBytes(StandardCharsets.UTF_8);
connection.setDoOutput(true);
}
@@ -186,9 +187,9 @@ public void execute() throws IOException {
int port = uri.getPort() > 0 ? uri.getPort() : 80;
Socket socket = new Socket(uri.getHost(), port);
PrintWriter writer =
- new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
+ new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),StandardCharsets.UTF_8), true);
BufferedReader reader =
- new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));
// send request
writer.print(method.name());
diff --git a/src/com/connectsdk/service/AirPlayService.java b/src/com/connectsdk/service/AirPlayService.java
index 46eb038e..768f379b 100644
--- a/src/com/connectsdk/service/AirPlayService.java
+++ b/src/com/connectsdk/service/AirPlayService.java
@@ -20,11 +20,8 @@
package com.connectsdk.service;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.util.Log;
-
import com.connectsdk.core.ImageInfo;
+import com.connectsdk.core.Log;
import com.connectsdk.core.MediaInfo;
import com.connectsdk.core.Util;
import com.connectsdk.discovery.DiscoveryFilter;
@@ -45,9 +42,11 @@
import com.connectsdk.service.sessions.LaunchSession;
import com.connectsdk.service.sessions.LaunchSession.LaunchSessionType;
+import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
+import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -55,6 +54,7 @@
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
@@ -66,12 +66,14 @@
import java.util.TimerTask;
import java.util.UUID;
+import javax.imageio.ImageIO;
+
public class AirPlayService extends DeviceService implements MediaPlayer, MediaControl {
public static final String X_APPLE_SESSION_ID = "X-Apple-Session-ID";
public static final String ID = "AirPlay";
private static final long KEEP_ALIVE_PERIOD = 15000;
- private final static String CHARSET = "UTF-8";
+ //private final static String CHARSET = "UTF-8";
private String mSessionId;
@@ -214,7 +216,7 @@ public void onGetPlaybackPositionFailed(ServiceCommandError error) {
/**
* AirPlay has the same response for Buffering and Finished states that's why this method
* always returns Finished state for video which is not ready to play.
- * @param listener
+ * @param listener the play state listener
*/
@Override
public void getPlayState(final PlayStateListener listener) {
@@ -381,33 +383,10 @@ public void onError(ServiceCommandError error) {
try {
URL imagePath = new URL(url);
- HttpURLConnection connection = (HttpURLConnection) imagePath.openConnection();
- connection.setInstanceFollowRedirects(true);
- connection.setDoInput(true);
- connection.connect();
-
- int responseCode = connection.getResponseCode();
- boolean redirect = (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
- || responseCode == HttpURLConnection.HTTP_MOVED_PERM
- || responseCode == HttpURLConnection.HTTP_SEE_OTHER);
-
- if(redirect) {
- String newPath = connection.getHeaderField("Location");
- URL newImagePath = new URL(newPath);
- connection = (HttpURLConnection) newImagePath.openConnection();
- connection.setInstanceFollowRedirects(true);
- connection.setDoInput(true);
- connection.connect();
- }
-
- InputStream input = connection.getInputStream();
- Bitmap myBitmap = BitmapFactory.decodeStream(input);
-
+ BufferedImage image = ImageIO.read(imagePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
- myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
+ ImageIO.write(image, "jpg", stream);
payload = stream.toByteArray();
- } catch (MalformedURLException e) {
- e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
@@ -632,7 +611,7 @@ String getAuthenticate(String method, String digestURI, String authStr) {
String digestAuthentication(String md5) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
- byte[] digest = md.digest(md5.getBytes());
+ byte[] digest = md.digest(md5.getBytes(StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xFF));
diff --git a/src/com/connectsdk/service/DIALService.java b/src/com/connectsdk/service/DIALService.java
index 475bcb93..e010a8d7 100644
--- a/src/com/connectsdk/service/DIALService.java
+++ b/src/com/connectsdk/service/DIALService.java
@@ -20,9 +20,8 @@
package com.connectsdk.service;
-import android.util.Log;
-
import com.connectsdk.core.AppInfo;
+import com.connectsdk.core.Log;
import com.connectsdk.core.Util;
import com.connectsdk.discovery.DiscoveryFilter;
import com.connectsdk.etc.helper.DeviceServiceReachability;
@@ -54,6 +53,7 @@ public class DIALService extends DeviceService implements Launcher {
public static final String ID = "DIAL";
private static final String APP_NETFLIX = "Netflix";
+ private static final String APP_YOUTUBE = "YouTube";
private static List registeredApps = new ArrayList();
@@ -115,11 +115,11 @@ public CapabilityPriorityLevel getLauncherCapabilityLevel() {
}
@Override
- public void launchApp(String appId, AppLaunchListener listener) {
+ public void launchApp(String appId, ResponseListener listener) {
launchApp(appId, null, listener);
}
- private void launchApp(String appId, JSONObject params, AppLaunchListener listener) {
+ private void launchApp(String appId, JSONObject params, ResponseListener listener) {
if (appId == null || appId.length() == 0) {
Util.postError(listener, new ServiceCommandError(0, "Must pass a valid appId", null));
return;
@@ -133,12 +133,12 @@ private void launchApp(String appId, JSONObject params, AppLaunchListener listen
}
@Override
- public void launchAppWithInfo(AppInfo appInfo, AppLaunchListener listener) {
+ public void launchAppWithInfo(AppInfo appInfo, ResponseListener listener) {
launchAppWithInfo(appInfo, null, listener);
}
@Override
- public void launchAppWithInfo(final AppInfo appInfo, Object params, final AppLaunchListener listener) {
+ public void launchAppWithInfo(final AppInfo appInfo, Object params, final ResponseListener listener) {
ServiceCommand> command =
new ServiceCommand>(getCommandProcessor(),
requestURL(appInfo.getName()), params, new ResponseListener