Checking miracast compatible devices using android app - android

How can I search for Miracast compatible devices (may be using WiFi Direct) in android?
I just got to know that DisplayManager and Presentation class in Android 4.2 help in presentation & miracast. But is there any way I can check if the other device is Miracast compatible / search Miracast sink?
Thanks
Smitha

android framework source codes shows how to search miracast sink devices.
basically using WiFi Direct devices search API,
discoverPeers -> requestPeers -> isWifiDisplay & isPrimarySinkDeviceType
private static boolean isWifiDisplay(WifiP2pDevice device) {
return device.wfdInfo != null
&& device.wfdInfo.isWfdEnabled()
&& isPrimarySinkDeviceType(device.wfdInfo.getDeviceType());
}
private static boolean isPrimarySinkDeviceType(int deviceType) {
return deviceType == WifiP2pWfdInfo.PRIMARY_SINK
|| deviceType == WifiP2pWfdInfo.SOURCE_OR_PRIMARY_SINK;
}
https://github.com/kensuke/How-to-Miracast-on-AOSP/wiki/wfd_scan
WifiP2pWfdInfo defined four device types,
public static final int WFD_SOURCE = 0;
public static final int PRIMARY_SINK = 1;
public static final int SECONDARY_SINK = 2;
public static final int SOURCE_OR_PRIMARY_SINK = 3;
http s://android.googlesource.com/platform/frameworks/base/+/master/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java
if you don't familiar with wifi direct, maybe my app is useful for using wifi direct api.
http s://github.com/kensuke/WiFiDirectTestApp
ADD: 2014/02/24 - parse toString output String for recognize Miracast devices Source or Sink
Wi-Fi Direct API requestPeers() callback to onPeersAvailable(), this method's parameter WifiP2pDeviceList has near by P2p devices that is a list of WifiP2pDevice instances, WifiP2pDevice has one device Wi-fi Direct information including Miracast information(wfd..) and device into can get uses WifiP2pDevice.toString() method.
Search "WFD DeviceInfo: XXX" String, XXX is a numerical value, masked "0x03" (see WifiP2pWfdInfo.java), after masked we get 0-3. That value defined SOURCE or SINK, see WifiP2pWfdInfo.java constants).
private static final int WFD_SOURCE = 0;
private static final int PRIMARY_SINK = 1;
private static final int SECONDARY_SINK = 2;
private static final int SOURCE_OR_PRIMARY_SINK = 3;
This very duty way can using on non rooted device, general app.
Sample of WifiP2pDevice.toString() returned value
"Device: ZTS1145
deviceAddress: 7a:e8:b6:f6:4d:74
primary type: 10-0050F204-5
secondary type: null
wps: 392
grpcapab: 0
devcapab: 33
status: 3
wfdInfo: WFD enabled: trueWFD DeviceInfo: 273
WFD CtrlPort: 7236
WFD MaxThroughput: 10"
// callback method of requestPeers();
public void onPeersAvailable(WifiP2pDeviceList peers) {
List<WifiP2pDevice> devs = new ArrayList<WifiP2pDevice>(peers.getDeviceList());
for (int i = 0; i < devs.size(); i++) {
WifiP2pDevice dev = devs.get(i);
boolean src = isWifiDisplaySource(dev);
boolean sink = isWifiDisplaySink(dev);
Log.d(TAG, dev.deviceName + " isSource[" + src + "] isSink[" + sink + "]");
}
}
private static final int WFD_DISABLED = -1;
private static final int WFD_SOURCE = 0;
private static final int PRIMARY_SINK = 1;
private static final int SECONDARY_SINK = 2;
private static final int SOURCE_OR_PRIMARY_SINK = 3;
private static final int DEVICE_TYPE = 0x3;
private int getWFDDeviceInfoFromString(String devStr) {
if (devStr == null) {
return WFD_DISABLED;
}
boolean wfd = false;
for (String line : devStr.split("\n")) {
// start self parsing...
// TODO: sprintf parse is more easy
// search "WFD enabled: [true|false]"
if (!line.matches(".*WFD enabled:.*")) {
continue;
}
String[] tokens = line.split(":");
int toks = tokens.length;
for (int i = 0; i < toks - 1; i++) {
if (!tokens[i].contains("WFD enabled")) {
continue;
}
String tok = tokens[i + 1].replaceAll("\\s", ""); // delete white space
if (tok.startsWith("true")) {
wfd = true;
break;
}
// why didn't use .equals() instead of .contains() and .startsWith() ? because
// 1) "wfdInfo: WFD enabled: trueWFD DeviceInfo: 273" // inputed string
// 2) "(wfdInfo):( WFD enabled):( trueWFD DeviceInfo):( 273)" // : splited string
// 3) "( trueWFD DeviceInfo)" => "trueWFD DeviceInfo" // white space deleted
}
}
if (!wfd) {
return WFD_DISABLED;
}
for (String line : devStr.split("\n")) {
// search "WFD DeviceInfo: \d+"
if (!line.matches(".*WFD DeviceInfo:.*")) {
continue;
}
String[] tokens = line.split(":");
int toks = tokens.length;
for (int i = 0; i < toks - 1; i++) {
if (!tokens[i].contains("WFD DeviceInfo")) {
continue;
}
String tok = tokens[i + 1].replaceAll("\\s", "");
int deviceInfo = Integer.parseInt(tok);
Log.d(TAG, "line[" + line + "] DeviceInfo[" + deviceInfo + "] masked[" + (deviceInfo & DEVICE_TYPE) + "]");
return deviceInfo;
}
}
return WFD_DISABLED;
}
private boolean isWifiDisplaySource(WifiP2pDevice dev) {
if (dev == null) {
return false;
}
int deviceInfo = getWFDDeviceInfoFromString(dev.toString());
if (deviceInfo == WFD_DISABLED) {
return false;
}
int deviceType = deviceInfo & DEVICE_TYPE; // masked
return deviceType == WFD_SOURCE || deviceType == SOURCE_OR_PRIMARY_SINK;
}
private boolean isWifiDisplaySink(WifiP2pDevice dev) {
if (dev == null) {
return false;
}
int deviceInfo = getWFDDeviceInfoFromString(dev.toString());
if (deviceInfo == WFD_DISABLED) {
return false;
}
int deviceType = deviceInfo & DEVICE_TYPE; // masked
return deviceType == PRIMARY_SINK || deviceType == SOURCE_OR_PRIMARY_SINK;
}

Related

Calculating combination in Android Studio

I have a javascript to calculate combination and works great. But when I tried to work on Android studio code it gets wrong result.
Js
var n=16;
var r=2;
function faktor(sayi) {
var sonuc=1;
for(var i=1;i<=sayi;i++)
{
sonuc*=i;
}
return sonuc;
}
function calculate (){
var sonuc2=faktor(n)/(faktor(r)*faktor(n-r));
console.log(sonuc2);
}
calculate();
Console log = 120
That's how I used in Android Studio
public static int tiklanan = 16;
public static int kombinasyon = 2;
int sonuc2;
private int faktor(int sayi){
int sonuc=1;
for(int i=1;i<=sayi;i++)
{
sonuc*=i;
}
return sonuc;
}
private void posibilityhesapla(){
sonuc2=faktor(tiklanan)/(faktor(kombinasyon)*faktor(tiklanan-kombinasyon));
Toast.makeText(this, "/"+sonuc2, Toast.LENGTH_SHORT).show();
}
sonuc2 always returns -1 but it must 120.
What I'm missing here ?
#Dorbagna your Integer variable has overflowed the value. Converting sonuc from int to long will fix your issue.
faktor(tiklanan) = faktor(16) = 20922789888000
While maximum value int can hold is 2147483647 (Integer.MAX_VALUE)
public static int tiklanan = 16;
public static int kombinasyon = 2;
// Change variable int type to long
long sonuc2;
//change return type to long
private long faktor(int sayi) {
// Change local variable int type to long
long sonuc = 1;
for (int i = 1; i <= sayi; i++) {
sonuc *= i;
}
return sonuc;
}
private void posibilityhesapla() {
sonuc2 = faktor(tiklanan) / (faktor(kombinasyon) * faktor(tiklanan - kombinasyon));
Toast.makeText(this, "/" + sonuc2, Toast.LENGTH_SHORT).show();
}

ExoPlayer Hls quality

I have ExoPlayer which plays HLS videos, the thing is i need to give user ability to change video quality(auto/1080/720/480).
I figured out that playing around with AdaptiveTrackSelection.Factory does set the quality, but it remains till the object is killed.
I have also tried using MappingTrackSelector, i know that my video has 4 tracks, but i did not get how to select any of it manually. Will this selection make it work?
Thanks for any ideas.
MappingTrackSelector.MappedTrackInfo trackInfo = mDefaultTrackSelector.getCurrentMappedTrackInfo();
mDefaultTrackSelector.selectTracks(
//what should go here?
, trackInfo.getTrackGroups(4));
Regarding this thread :https://github.com/google/ExoPlayer/issues/2250, I managed to change exo player video quality while playing previous one, so it does not getting in buffering instantly.
So I have next classes :
public enum HLSQuality {
Auto, Quality1080, Quality720, Quality480, NoValue
}
class HLSUtil {
private HLSUtil() {
}
#NonNull
static HLSQuality getQuality(#NonNull Format format) {
switch (format.height) {
case 1080: {
return HLSQuality.Quality1080;
}
case 720: {
return HLSQuality.Quality720;
}
case 480:
case 486: {
return HLSQuality.Quality480;
}
default: {
return HLSQuality.NoValue;
}
}
}
static boolean isQualityPlayable(#NonNull Format format) {
return format.height <= 1080;
}
}
public class ClassAdaptiveTrackSelection extends BaseTrackSelection {
public static final class Factory implements TrackSelection.Factory {
private final BandwidthMeter bandwidthMeter;
private final int maxInitialBitrate = 2000000;
private final int minDurationForQualityIncreaseMs = 10000;
private final int maxDurationForQualityDecreaseMs = 25000;
private final int minDurationToRetainAfterDiscardMs = 25000;
private final float bandwidthFraction = 0.75f;
private final float bufferedFractionToLiveEdgeForQualityIncrease = 0.75f;
public Factory(BandwidthMeter bandwidthMeter) {
this.bandwidthMeter = bandwidthMeter;
}
#Override
public ClassAdaptiveTrackSelection createTrackSelection(TrackGroup group, int... tracks) {
Log.d(ClassAdaptiveTrackSelection.class.getSimpleName(), " Video player quality reset to Auto");
sHLSQuality = HLSQuality.Auto;
return new ClassAdaptiveTrackSelection(
group,
tracks,
bandwidthMeter,
maxInitialBitrate,
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
bufferedFractionToLiveEdgeForQualityIncrease
);
}
}
private static HLSQuality sHLSQuality = HLSQuality.Auto;
private final BandwidthMeter bandwidthMeter;
private final int maxInitialBitrate;
private final long minDurationForQualityIncreaseUs;
private final long maxDurationForQualityDecreaseUs;
private final long minDurationToRetainAfterDiscardUs;
private final float bandwidthFraction;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private int selectedIndex;
private int reason;
private ClassAdaptiveTrackSelection(TrackGroup group,
int[] tracks,
BandwidthMeter bandwidthMeter,
int maxInitialBitrate,
long minDurationForQualityIncreaseMs,
long maxDurationForQualityDecreaseMs,
long minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease) {
super(group, tracks);
this.bandwidthMeter = bandwidthMeter;
this.maxInitialBitrate = maxInitialBitrate;
this.minDurationForQualityIncreaseUs = minDurationForQualityIncreaseMs * 1000L;
this.maxDurationForQualityDecreaseUs = maxDurationForQualityDecreaseMs * 1000L;
this.minDurationToRetainAfterDiscardUs = minDurationToRetainAfterDiscardMs * 1000L;
this.bandwidthFraction = bandwidthFraction;
this.bufferedFractionToLiveEdgeForQualityIncrease = bufferedFractionToLiveEdgeForQualityIncrease;
selectedIndex = determineIdealSelectedIndex(Long.MIN_VALUE);
reason = C.SELECTION_REASON_INITIAL;
}
#Override
public void updateSelectedTrack(long playbackPositionUs, long bufferedDurationUs, long availableDurationUs) {
long nowMs = SystemClock.elapsedRealtime();
// Stash the current selection, then make a new one.
int currentSelectedIndex = selectedIndex;
selectedIndex = determineIdealSelectedIndex(nowMs);
if (selectedIndex == currentSelectedIndex) {
return;
}
if (!isBlacklisted(currentSelectedIndex, nowMs)) {
// Revert back to the current selection if conditions are not suitable for switching.
Format currentFormat = getFormat(currentSelectedIndex);
Format selectedFormat = getFormat(selectedIndex);
if (selectedFormat.bitrate > currentFormat.bitrate
&& bufferedDurationUs < minDurationForQualityIncreaseUs(availableDurationUs)) {
// The selected track is a higher quality, but we have insufficient buffer to safely switch
// up. Defer switching up for now.
selectedIndex = currentSelectedIndex;
} else if (selectedFormat.bitrate < currentFormat.bitrate
&& bufferedDurationUs >= maxDurationForQualityDecreaseUs) {
// The selected track is a lower quality, but we have sufficient buffer to defer switching
// down for now.
selectedIndex = currentSelectedIndex;
}
}
// If we adapted, update the trigger.
if (selectedIndex != currentSelectedIndex) {
reason = C.SELECTION_REASON_ADAPTIVE;
}
}
#Override
public int getSelectedIndex() {
return selectedIndex;
}
#Override
public int getSelectionReason() {
return reason;
}
#Override
public Object getSelectionData() {
return null;
}
#Override
public int evaluateQueueSize(long playbackPositionUs, List<? extends MediaChunk> queue) {
if (queue.isEmpty()) {
return 0;
}
int queueSize = queue.size();
long bufferedDurationUs = queue.get(queueSize - 1).endTimeUs - playbackPositionUs;
if (bufferedDurationUs < minDurationToRetainAfterDiscardUs) {
return queueSize;
}
int idealSelectedIndex = determineIdealSelectedIndex(SystemClock.elapsedRealtime());
Format idealFormat = getFormat(idealSelectedIndex);
// If the chunks contain video, discard from the first SD chunk beyond
// minDurationToRetainAfterDiscardUs whose resolution and bitrate are both lower than the ideal
// track.
for (int i = 0; i < queueSize; i++) {
MediaChunk chunk = queue.get(i);
Format format = chunk.trackFormat;
long durationBeforeThisChunkUs = chunk.startTimeUs - playbackPositionUs;
if (durationBeforeThisChunkUs >= minDurationToRetainAfterDiscardUs
&& format.bitrate < idealFormat.bitrate
&& format.height != Format.NO_VALUE && format.height < 720
&& format.width != Format.NO_VALUE && format.width < 1280
&& format.height < idealFormat.height) {
return i;
}
}
return queueSize;
}
private int determineIdealSelectedIndex(long nowMs) {
if (sHLSQuality != HLSQuality.Auto) {
Log.d(ClassAdaptiveTrackSelection.class.getSimpleName(), " Video player quality seeking for " + String.valueOf(sHLSQuality));
for (int i = 0; i < length; i++) {
Format format = getFormat(i);
if (HLSUtil.getQuality(format) == sHLSQuality) {
Log.d(ClassAdaptiveTrackSelection.class.getSimpleName(), " Video player quality set to " + String.valueOf(sHLSQuality));
return i;
}
}
}
Log.d(ClassAdaptiveTrackSelection.class.getSimpleName(), " Video player quality seeking for auto quality " + String.valueOf(sHLSQuality));
long bitrateEstimate = bandwidthMeter.getBitrateEstimate();
long effectiveBitrate = bitrateEstimate == BandwidthMeter.NO_ESTIMATE
? maxInitialBitrate : (long) (bitrateEstimate * bandwidthFraction);
int lowestBitrateNonBlacklistedIndex = 0;
for (int i = 0; i < length; i++) {
if (nowMs == Long.MIN_VALUE || !isBlacklisted(i, nowMs)) {
Format format = getFormat(i);
if (format.bitrate <= effectiveBitrate && HLSUtil.isQualityPlayable(format)) {
Log.d(ClassAdaptiveTrackSelection.class.getSimpleName(), " Video player quality auto quality found " + String.valueOf(sHLSQuality));
return i;
} else {
lowestBitrateNonBlacklistedIndex = i;
}
}
}
return lowestBitrateNonBlacklistedIndex;
}
private long minDurationForQualityIncreaseUs(long availableDurationUs) {
boolean isAvailableDurationTooShort = availableDurationUs != C.TIME_UNSET
&& availableDurationUs <= minDurationForQualityIncreaseUs;
return isAvailableDurationTooShort
? (long) (availableDurationUs * bufferedFractionToLiveEdgeForQualityIncrease)
: minDurationForQualityIncreaseUs;
}
static void setHLSQuality(HLSQuality HLSQuality) {
sHLSQuality = HLSQuality;
}
}
Hope it helps someone.
You can check out ExoPlayer_TrackSelection from github for changing video quality manually.

Comparison of app version

How to compare app version in android
I got latest version code and current version code , but the problem is
current version is 1.0
and latest version is 1.0.0
so how to compare that float value in android
I have written a small Android library for comparing version numbers: https://github.com/G00fY2/version-compare
What it basically does is this:
public int compareVersions(String versionA, String versionB) {
String[] versionTokensA = versionA.split("\\.");
String[] versionTokensB = versionB.split("\\.");
List<Integer> versionNumbersA = new ArrayList<>();
List<Integer> versionNumbersB = new ArrayList<>();
for (String versionToken : versionTokensA) {
versionNumbersA.add(Integer.parseInt(versionToken));
}
for (String versionToken : versionTokensB) {
versionNumbersB.add(Integer.parseInt(versionToken));
}
final int versionASize = versionNumbersA.size();
final int versionBSize = versionNumbersB.size();
int maxSize = Math.max(versionASize, versionBSize);
for (int i = 0; i < maxSize; i++) {
if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return 1;
} else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return -1;
}
}
return 0;
}
This snippet doesn't offer any error checks or handling. Beside that my library also supports suffixes like "1.2-rc" > "1.2-beta".
I am a bit late to the party but I have a great solution for all of you!
1. Use this class:
public class VersionComparator implements Comparator {
public boolean equals(Object o1, Object o2) {
return compare(o1, o2) == 0;
}
public int compare(Object o1, Object o2) {
String version1 = (String) o1;
String version2 = (String) o2;
VersionTokenizer tokenizer1 = new VersionTokenizer(version1);
VersionTokenizer tokenizer2 = new VersionTokenizer(version2);
int number1, number2;
String suffix1, suffix2;
while (tokenizer1.MoveNext()) {
if (!tokenizer2.MoveNext()) {
do {
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
if (number1 != 0 || suffix1.length() != 0) {
// Version one is longer than number two, and non-zero
return 1;
}
}
while (tokenizer1.MoveNext());
// Version one is longer than version two, but zero
return 0;
}
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number1 < number2) {
// Number one is less than number two
return -1;
}
if (number1 > number2) {
// Number one is greater than number two
return 1;
}
boolean empty1 = suffix1.length() == 0;
boolean empty2 = suffix2.length() == 0;
if (empty1 && empty2) continue; // No suffixes
if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)
if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)
// Lexical comparison of suffixes
int result = suffix1.compareTo(suffix2);
if (result != 0) return result;
}
if (tokenizer2.MoveNext()) {
do {
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number2 != 0 || suffix2.length() != 0) {
// Version one is longer than version two, and non-zero
return -1;
}
}
while (tokenizer2.MoveNext());
// Version two is longer than version one, but zero
return 0;
}
return 0;
}
// VersionTokenizer.java
public static class VersionTokenizer {
private final String _versionString;
private final int _length;
private int _position;
private int _number;
private String _suffix;
private boolean _hasValue;
VersionTokenizer(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
_versionString = versionString;
_length = versionString.length();
}
public int getNumber() {
return _number;
}
String getSuffix() {
return _suffix;
}
public boolean hasValue() {
return _hasValue;
}
boolean MoveNext() {
_number = 0;
_suffix = "";
_hasValue = false;
// No more characters
if (_position >= _length)
return false;
_hasValue = true;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c < '0' || c > '9') break;
_number = _number * 10 + (c - '0');
_position++;
}
int suffixStart = _position;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c == '.') break;
_position++;
}
_suffix = _versionString.substring(suffixStart, _position);
if (_position < _length) _position++;
return true;
}
}
}
2. create this function
private fun isNewVersionAvailable(currentVersion: String, latestVersion: String): Boolean {
val versionComparator = VersionComparator()
val result: Int = versionComparator.compare(currentVersion, latestVersion)
var op = "=="
if (result < 0) op = "<"
if (result > 0) op = ">"
System.out.printf("%s %s %s\n", currentVersion, op, latestVersion)
return if (op == ">" || op == "==") {
false
} else op == "<"
}
3. and just call it by
e.g. isNewVersionAvailable("1.2.8","1.2.9") where 1.2.8 is your current version here and 1.2.9 is the latest version, which returns true!
Why overcomplicate this so much?
Just scale the major, minor, patch version and you have it covered:
fun getAppVersionFromString(version: String): Int { // "2.3.5"
val versions = version.split(".") // [2, 3, 5]
val major = versions[0].toIntOrDefault(0) * 10000 // 20000
val minor = versions[1].toIntOrDefault(0) * 1000 // 3000
val patch = versions[2].toIntOrDefault(0) * 100 // 500
return major + minor + patch // 2350
}
That way when you compare e.g 9.10.10 with 10.0.0 the second one is greater.
Use the following method to compare the versions number:
Convert float to String first.
public static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
}
Refer the following SO question : Efficient way to compare version strings in Java

Store all users information in a in custom class which are currently in room, i'm using smartfoxServer

i'm using custom class to store user specific information class is as under:
using UnityEngine;
using System.Collections;
public class RoomPlayerInfo {
private int minutes;
private int seconds;
private int miliSecond;
private string userName;
public int Minutes{
get{ return minutes; }
set{ minutes = value;}
}
public int Seconds{
get{ return seconds; }
set{ seconds = value; }
}
public string UserName{
get{ return userName; }
set{ userName = value; }
}
public int MiliSecond{
get{ return miliSecond;}
set{ miliSecond = value;}
}
}
i'm adding user at runtime in a list:
private List<RoomPlayerInfo> listRoomPlayerInfo = new List<RoomPlayerInfo> ();
RoomPlayerInfo rPI = new RoomPlayerInfo ();
rPI.Minutes = diff.Minutes;
rPI.Seconds = diff.Seconds;
rPI.MiliSecond = diff.Milliseconds;
rPI.UserName = sfs.MySelf.Name;
listRoomPlayerInfo.Add (rPI);
When i'm going to remove a player at runtime, it only remove the currentPlayer on each device, mean on each device remove the own player of such device, but i'm going to remove the player which take max time in game..
How i can done my job ???
void RemovePlayer()
{
int i = 0;
int removePlayerIndex = 0;
if (listRoomPlayerInfo != null) {
string playerID = listRoomPlayerInfo [i].UserName;
for (; i < listRoomPlayerInfo.Count -1; i++) {
if (listRoomPlayerInfo [i + 1].Minutes >= listRoomPlayerInfo [i].Minutes && listRoomPlayerInfo [i + 1].Seconds > listRoomPlayerInfo [i].Seconds && listRoomPlayerInfo[i+1].MiliSecond > listRoomPlayerInfo[i].MiliSecond) {
playerID = listRoomPlayerInfo [i + 1].UserName;
removePlayerIndex = i + 1;
}
}
removeUserName.text = playerID + " Remove from room...";
listRoomPlayerInfo.Remove (listRoomPlayerInfo [removePlayerIndex]);
}
}

Connect to a Public wifi Network from Android Code?

I am developing an Android App that requires me to scan all available public wifi networks and connect to the one with highest signal strength. Can this be achieved is so HOW?
Right now my app just turns on wifi and connects to a saved network.
First have a look at the official help:
http://developer.android.com/reference/android/net/wifi/WifiManager.html
then look around and found something like that:
How can I get Android Wifi Scan Results into a list?
ScanResult gives the rssi (level)that can be used to select the appropriate network:
http://developer.android.com/reference/android/net/wifi/ScanResult.html
Here's a simple code to scan:
WifiManager wifi= (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.startScan();
// get list of the results in object format ( like an array )
List<ScanResult> results = wifi.getScanResults();`
// loop that goes through list
for (ScanResult result : results) {
Toast.makeText(this, result.SSID + " " + result.level,
Toast.LENGTH_SHORT).show();
}
Remember you need permsissions in your manifest.xml:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
UPDATE:
To create a network by SSID I use the following:
private boolean addNetworkAndActivate(ScanResult scanResult) {
WifiConfiguration wc = null;
List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : configs) {
try {
if (wifiConfiguration.SSID.equals("\"" + scanResult.SSID + "\"")) {
wc = wifiConfiguration;
break;
}
} catch (Exception e) {
}
}
// not configured, create new
if (wc == null) {
wc = new WifiConfiguration();
ConfigurationSecuritiesV8 conf = new ConfigurationSecuritiesV8();
conf.setupSecurity(wc, conf.getScanResultSecurity(scanResult), "7ej8e4jka9");
wc.SSID = "\"" + scanResult.SSID + "\"";
int res = wifiManager.addNetwork(wc);
if (res == -1)
return false;
if (!wifiManager.saveConfiguration())
return false;
}
boolean active = wifiManager.enableNetwork(wc.networkId, true);
return active;
}
Classes:
public class ConfigurationSecuritiesV8 extends ConfigurationSecurities {
static final int SECURITY_NONE = 0;
static final int SECURITY_WEP = 1;
static final int SECURITY_PSK = 2;
static final int SECURITY_EAP = 3;
enum PskType {
UNKNOWN, WPA, WPA2, WPA_WPA2
}
private static final String TAG = "ConfigurationSecuritiesV14";
private static int getSecurity(WifiConfiguration config) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
return SECURITY_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return SECURITY_EAP;
}
return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
}
private static int getSecurity(ScanResult result) {
if (result.capabilities.contains("WEP")) {
return SECURITY_WEP;
} else if (result.capabilities.contains("PSK")) {
return SECURITY_PSK;
} else if (result.capabilities.contains("EAP")) {
return SECURITY_EAP;
}
return SECURITY_NONE;
}
#Override
public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) {
return String.valueOf(getSecurity(wifiConfig));
}
#Override
public String getScanResultSecurity(ScanResult scanResult) {
return String.valueOf(getSecurity(scanResult));
}
#Override
public void setupSecurity(WifiConfiguration config, String security, String password) {
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
final int sec = security == null ? SECURITY_NONE : Integer.valueOf(security);
final int passwordLen = password == null ? 0 : password.length();
switch (sec) {
case SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
break;
case SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (passwordLen != 0) {
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((passwordLen == 10 || passwordLen == 26 || passwordLen == 58) && password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
break;
case SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (passwordLen != 0) {
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
break;
case SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
// config.eap.setValue((String)
// mEapMethodSpinner.getSelectedItem());
//
// config.phase2.setValue((mPhase2Spinner.getSelectedItemPosition()
// == 0) ? "" :
// "auth=" + mPhase2Spinner.getSelectedItem());
// config.ca_cert.setValue((mEapCaCertSpinner.getSelectedItemPosition()
// == 0) ? "" :
// KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
// (String) mEapCaCertSpinner.getSelectedItem());
// config.client_cert.setValue((mEapUserCertSpinner.getSelectedItemPosition()
// == 0) ?
// "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
// (String) mEapUserCertSpinner.getSelectedItem());
// config.private_key.setValue((mEapUserCertSpinner.getSelectedItemPosition()
// == 0) ?
// "" : KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
// (String) mEapUserCertSpinner.getSelectedItem());
// config.identity.setValue((mEapIdentityView.length() == 0) ? "" :
// mEapIdentityView.getText().toString());
// config.anonymous_identity.setValue((mEapAnonymousView.length() ==
// 0) ? "" :
// mEapAnonymousView.getText().toString());
// if (mPasswordView.length() != 0) {
// config.password.setValue(mPasswordView.getText().toString());
// }
break;
default:
LogBridge.d(TAG, "Invalid security type: " + sec);
}
// config.proxySettings = mProxySettings;
// config.ipAssignment = mIpAssignment;
// config.linkProperties = new LinkProperties(mLinkProperties);
}
private static PskType getPskType(ScanResult result) {
boolean wpa = result.capabilities.contains("WPA-PSK");
boolean wpa2 = result.capabilities.contains("WPA2-PSK");
if (wpa2 && wpa) {
return PskType.WPA_WPA2;
} else if (wpa2) {
return PskType.WPA2;
} else if (wpa) {
return PskType.WPA;
} else {
LogBridge.d(TAG, "Received abnormal flag string: " + result.capabilities);
return PskType.UNKNOWN;
}
}
#Override
public String getDisplaySecirityString(final ScanResult scanResult) {
final int security = getSecurity(scanResult);
if (security == SECURITY_PSK) {
switch (getPskType(scanResult)) {
case WPA:
return "WPA";
case WPA_WPA2:
case WPA2:
return "WPA2";
default:
return "?";
}
} else {
switch (security) {
case SECURITY_NONE:
return "OPEN";
case SECURITY_WEP:
return "WEP";
case SECURITY_EAP:
return "EAP";
}
}
return "?";
}
#Override
public boolean isOpenNetwork(String security) {
return String.valueOf(SECURITY_NONE).equals(security);
}
}
And
public abstract class ConfigurationSecurities {
/**
* #return The security of a given {#link WifiConfiguration}.
*/
public abstract String getWifiConfigurationSecurity(WifiConfiguration wifiConfig);
/**
* #return The security of a given {#link ScanResult}.
*/
public abstract String getScanResultSecurity(ScanResult scanResult);
/**
* Fill in the security fields of WifiConfiguration config.
*
* #param config
* The object to fill.
* #param security
* If is OPEN, password is ignored.
* #param password
* Password of the network if security is not OPEN.
*/
public abstract void setupSecurity(WifiConfiguration config, String security, final String password);
public abstract String getDisplaySecirityString(final ScanResult scanResult);
public abstract boolean isOpenNetwork(final String security);
public static ConfigurationSecurities newInstance() {
// if (Version.SDK < 8) {
// return new ConfigurationSecuritiesOld();
// } else {
return new ConfigurationSecuritiesV8();
// }
}
}

Categories

Resources