i'm trying to make an app that can create a list of available wifi access point. here's part of the code i used:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (results != null) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + rssiString);
textStatus.append("\n");
}
unregisterReceiver(x); //stops the continuous scan
textState.setText("Scanning complete!");
} else {
unregisterReceiver(x);
textState.setText("Nothing is found. Please make sure you are under any wifi coverage");
}
}
};
both textStatus and textState is a TextView.
i can get this to work but sometimes the result shows duplicate SSID but with different signal level, in a single scan. there might be 3-4 same SSIDs but with different signal level.
is it really different SSIDs and what differs them? can anyone explain?
Are you having several router modems for the same network? For example: A company has a big wireless network with multiple router modems installed in several places so every room has Wifi. If you do that scan you will get a lot of results with the same SSIDs but with different acces points, and thus different signal level.
EDIT:
According to Walt's comment you can also have multiple results despite having only one access point if your modem is dual-band.
use below code to to remove duplicate ssids with highest signal strength
public void onReceive(Context c, Intent intent) {
ArrayList<ScanResult> mItems = new ArrayList<>();
List<ScanResult> results = wifiManager.getScanResults();
wifiListAdapter = new WifiListAdapter(ConnectToInternetActivity.this, mItems);
lv.setAdapter(wifiListAdapter);
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " "
+ result.capabilities;
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
wifiListAdapter.notifyDataSetChanged();
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) >
calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
wifiListAdapter.notifyDataSetChanged();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my simple Solution please and it is work for me
private void scanWifiListNew() {
wifiManager.startScan();
List<ScanResult> wifiList = wifiManager.getScanResults();
mWiFiList = new ArrayList<>();
for(ScanResult result: wifiList){
checkItemExists(mWiFiList, result);
}
setAdapter(mWiFiList);
}
private void printList(List<ScanResult> list){
for(ScanResult result: list){
int level = WifiManager.calculateSignalLevel(result.level, 100);
System.out.println(result.SSID + " Level is " + level + " out of 100");
}
}
private void checkItemExists(List<ScanResult> newWiFiList, ScanResult resultNew){
int indexToRemove = -1;
if(newWiFiList.size() > 0) {
for (int i = 0; i < newWiFiList.size(); i++) {
ScanResult resultCurrent = newWiFiList.get(i);
if (resultCurrent.SSID.equals(resultNew.SSID)) {
int levelCurrent = WifiManager.calculateSignalLevel(resultCurrent.level, 100);
int levelNew = WifiManager.calculateSignalLevel(resultNew.level, 100);
if (levelNew > levelCurrent) {
indexToRemove = i;
break;
}else indexToRemove = -2;
}
}
if(indexToRemove > -1){
newWiFiList.remove(indexToRemove);
newWiFiList.add(indexToRemove,resultNew);
}else if(indexToRemove == -1)newWiFiList.add(resultNew);
} else newWiFiList.add(resultNew);
}
private void setAdapter(List<ScanResult> list) {
listAdapter = new WifiListAdapter(getActivity().getApplicationContext(), list);
wifiListView.setAdapter(listAdapter);
}
Related
I used libUsbDotNet library (C#) to read data from USB device.
The program sees the device and turns to it, but gives a response IoTimedOut.
The program code is shown below.
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x10C4, 0xEA61);
public static UsbDevice MyUsbDevice;
public static void Main()
{
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
ErrorCode ec = ErrorCode.None;
int bytesRead = 0;
byte[] readBuffer = new byte[32];
while (true) {
Thread.Sleep(100);
ec = reader.Read(readBuffer, 1500, out bytesRead);
if (bytesRead > 0)
{
Console.WriteLine("Data Received");
// Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
else {
Console.Write("Error type: ");
Console.WriteLine(ec);
Console.ReadKey();
MyUsbDevice.Close();
break;
}
}
}
I tried to change the reading parameters but it doesn't help. Can you please tell me what it may be related to, it is not clear to me from the libUsbDotNet documentation?
Im trying to follow this tutorial:
//Build an ArrayList to hold all of the words that we get from the
imported tweets
ArrayList<String> words = new ArrayList();
void setup() { //Set the size of the stage, and the background to black.
size(550,550);
background(0);
smooth();
//Credentials ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("lPFSpjBppo5u4KI5xEXaQ");
cb.setOAuthConsumerSecret("SYt3e4xxSHUL1gPfM9bxQIq6Jf34Hln9T1q9KGCPs");
cb.setOAuthAccessToken("17049577-Yyo3AEVsqZZopPTr055TFdySop228pKKAZGbJDtnV");
cb.setOAuthAccessTokenSecret("6ZjJBebElMBiOOeyVeh8GFLsROtXXtKktXALxAT0I");
//Make the twitter object and prepare the query
Twitter twitter = new
TwitterFactory(cb.build()).getInstance();
Query query = new Query("#OWS");
query.setRpp(100);
//Try making the query request. try {
QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();
for (int i = 0; i < tweets.size(); i++) {
Tweet t = (Tweet) tweets.get(i);
String user = t.getFromUser();
String msg = t.getText();
Date d = t.getCreatedAt();
println("Tweet by " + user + " at " + d + ": " + msg);
//Break the tweet into words
String[] input = msg.split(" ");
for (int j = 0; j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
}; } catch (TwitterException te) {
println("Couldn't connect: " + te); }; } void draw() { //Draw a faint black rectangle over what is currently on the stage so
it fades over time. fill(0,1); rect(0,0,width,height);
//Draw a word from the list of words that we've built int i = (frameCount % words.size()); String word = words.get(i);
//Put it somewhere random on the stage, with a random size and colour fill(255,random(50,150)); textSize(random(10,30));
text(word, random(width), random(height)); }
But i get the following error when i run the code in processing. cannot find class or type named tweet
Ive added the twitter4j libraries by dragging and dropping to the processing IDE.
Im using processing 2.1 and twitter4j3.05
Any suggestions?
This is a basic example using twitter4j 3.0.5.
import java.util.*;
List<Status>statuses = null;
TwitterFactory twitterFactory;
Twitter twitter;
void setup() {
size(100, 100);
background(0);
connectTwitter();
getTimeline();
getSearchTweets();
}
void draw() {
background(0);
}
// Initial connection
void connectTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xxx");
cb.setOAuthConsumerSecret("xxx");
cb.setOAuthAccessToken("xxx");
cb.setOAuthAccessTokenSecret("xxx");
twitterFactory = new TwitterFactory(cb.build());
twitter = twitterFactory.getInstance();
println("connected");
}
// Get your tweets
void getTimeline() {
try {
statuses = twitter.getHomeTimeline();
}
catch(TwitterException e) {
println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
for (Status status:statuses) {
println(status.getUser().getName() + ": " + status.getText());
}
}
// Search for tweets
void getSearchTweets() {
try {
Query query = new Query("love");
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
println("#" + status.getUser().getScreenName() + ":" + status.getText());
}
}
catch (TwitterException e) {
println("Search tweets: " + e);
}
}
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
I am building an AppWorld sort of thing in blackberry.I have Categories,sub categories and apps within.I want to do in-app download,but as of now i am calling the browser and passing the url and downloading of the content happens.How to make in-app download or download from within my app just like the AppWorld of blackberry.
YOu need to use code module manager API to download and install applications.
Code in bits and pieces
_moduleGroup = new CodeModuleGroup(appVendorName);
_moduleGroup.setVersion(JADParser.getValue("MIDlet-Version"));
_moduleGroup.setVendor(vendorName);
_moduleGroup.setFriendlyName(appName);
_moduleGroup.setDescription(JADParser.getValue("MIDlet-Description"));
String dependency = JADParser.getValue("RIM-COD-Module-Dependencies");
if (dependency != null)
{
dependency = dependency.trim();
String[] dependencyList = vStringUtils.split(dependency, ',');
for (int i = 0; i < dependencyList.length; i++)
{
_moduleGroup.addDependency(dependencyList[i]);
}
}
for (i = 0; i < count; i++)
{
if (!writeCODFile(getCodFileData(i), getCodFileName(i)))
{
throw new Exception();
}
}
private boolean writeCODFile(byte[] data, String fileName)
{
boolean isSuccess = true;
int moduleId = 0;
if (data.length > MODULE_SIZE_LIMIT)
{
moduleId = CodeModuleManager.createNewModule(data.length, data, MODULE_SIZE_LIMIT);
isSuccess = CodeModuleManager.writeNewModule(moduleId, MODULE_SIZE_LIMIT, data, MODULE_SIZE_LIMIT, data.length - MODULE_SIZE_LIMIT);
}
else
{
moduleId = CodeModuleManager.createNewModule(data.length, data, data.length);
}
if (moduleId > 0 && isSuccess)
{
int ret = CodeModuleManager.saveNewModule(moduleId, true, _transactionId);
if (ret == CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN || ret == CodeModuleManager.CMM_OK)
{
return true;
}
}
return false;
}
I am developing an audio strreaming application and i am using Streamingplayer
now i want information about the currently playing song how can i obtain that?
It is not available as part of the url as it is shown in streamplayer api.
Does anybody has made such thing ealiar then please reply.
How can i update that when a song changes?
You can refer the link: http://www.smackfu.com/stuff/programming/shoutcast.html
and can use below code
void getMetaData(){
Thread metaDataThread = new Thread(new Runnable(){
public void run(){
try {
metaDataCheckBit = false;
StreamConnection streamConnection=null;
HttpConnection httpConnection = null;
InputStream inputStream =null;
streamConnection=(StreamConnection)Connector.open(newUrl);
httpConnection=(HttpConnection)streamConnection;
httpConnection.setRequestProperty("Icy-metadata", "1");
int httpStatus=httpConnection.getResponseCode();
if(httpStatus==HttpConnection.HTTP_OK){
String mint = httpConnection.getHeaderField("icy-metaint");
inputStream = streamConnection.openInputStream();
int length= Integer.parseInt(mint);
int b = 0;
int count =0;
while(count++ < length){
b = inputStream.read();
}
int metalength = ((int)b)*16;
if(metalength <= 0)return;
byte buf[] = new byte[metalength];
inputStream.read(buf,0,buf.length);
String metaData = new String(buf);
int streamTilleIndex = metaData.indexOf("StreamTitle");
// if(streamTilleIndex <= 0)return;
String streamTille = metaData.substring(streamTilleIndex);
int eqindex = streamTille.indexOf('=');
// if(eqindex <= 0){return;}
int colindex = streamTille.indexOf(';');
// if(colindex <= 0)return;
String metaDatam = streamTille.substring(eqindex, colindex);
int lengthOfMaetaDataM = metaDatam.length();
// if(lengthOfMaetaDataM <= 0){return;}
metaDataParsed =metaDatam.substring(2, lengthOfMaetaDataM-2);
if(metaDataParsed!="")
metaDataCheckBit = true;
}
}
catch (Exception e){
System.out.println(e);
}
}
});
metaDataThread.start();
}