How to get a list of names of Wi-Fi network and signal
I used the following method to fill the array.
It works on Android versions less than 5 only. and does not work on 6 or higher.
I want code that works on all versions.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
List myListrow = new List();
var wifiMgr = (WifiManager)GetSystemService(WifiService);
var wifiList = wifiMgr.ScanResults;
foreach (var item in wifiList)
{
var wifiLevel = WifiManager.CalculateSignalLevel(item.Level, 100);
myListrow.Add(($"Wifi Name: {item.Ssid} - Single: {wifiLevel}"));
}
Update:
Add the permission.ACCESS_COARSE_LOCATION permission. The original code works well.
The code used to list the all the names:
void getWifiList() {
IList myListrow = new ArrayList();
var wifiMgr = (WifiManager)GetSystemService(WifiService);
var wifiList = wifiMgr.ScanResults;
foreach (var item in wifiList)
{
var wifiLevel = WifiManager.CalculateSignalLevel(item.Level, 100);
myListrow.Add(($"Wifi Name: {item.Ssid} - Single: {wifiLevel}"));
}
}
The code to request permission:
private void RequestPermission()
{
Log.Info(TAG, " permission has NOT been granted. Requesting permission.");
if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessCoarseLocation))
{
Snackbar.Make(layout, Resource.String.permission_accesscoarselocation_rationale,
Snackbar.LengthIndefinite).SetAction(Resource.String.ok, new Action<View>(delegate (View obj) {
ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessCoarseLocation }, REQUEST_LOCATION);
})).Show();
}
else
{
// AccessCoarseLocation permission has not been granted yet. Request it directly.
ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessCoarseLocation }, REQUEST_LOCATION);
}
}
Screenshot:
You could download the source file from the link below.
https://github.com/WendyZang/Test/tree/master/Wi-Fi%20network/GetNetWorkInfo
I'm using Ionic 3 and this cordova plugin mauron85/cordova-plugin-background-geolocation but the app doesn't stream coordinates when it's in the background in iOS.
It works in Android, iOS emulator but not in a real iPhone. Also, the url option stops streaming after 1s
My code so far:
/**
*
* #param {boolean} status
* #param {number} stepOn
*/
private registerCoords(status: boolean, stepOn?: number): void {
let step: number = stepOn ? stepOn : 1;
if (!STATIC.GEO_INTERVAL && status) {
STATIC.GEO_INTERVAL = setInterval((() => {
this.currentCoords = this.geolocationService.getCoords();
if (!this.isNetWork) {
this.functions.f_alertToast('Network connection lost', 0);
return this.registerCoords(false);
}
if (!this.currentCoords && !this.isProcessPicture) {
this.geoLocationEvent = false;
this.isGeoLocation = false;
console.warn('[HomePage] registerCoords() -> setInterval() [GPS connection lost!!]');
}
else if (this.currentCoords) {
this.geoLocationEvent = true;
this.isGeoLocation = true;
}
this.saveCoords(this.currentCoords, step);
step = 1;
}).bind(this), STATIC.GEO_TIMEOUT);
this.finishLoad();
}
if (status === false) {
clearInterval(STATIC.GEO_INTERVAL);
STATIC.GEO_INTERVAL = null;
this.checkGeolocation();
}
}
config.xml
<plugin name="cordova-plugin-mauron85-background-geolocation" spec="2.3.5">
<variable name="ICON" value="#mipmap/icon" />
<variable name="SMALL_ICON" value="#mipmap/icon" />
<variable name="ACCOUNT_NAME" value="#string/app_name" />
<variable name="ACCOUNT_LABEL" value="#string/app_name" />
<variable name="ACCOUNT_TYPE" value="$PACKAGE_NAME.account" />
<variable name="CONTENT_AUTHORITY" value="$PACKAGE_NAME" />
<variable name="GOOGLE_PLAY_SERVICES_VERSION" value="11+" />
<variable name="ANDROID_SUPPORT_LIBRARY_VERSION" value="23+" />
</plugin>
<plugin name="cordova-plugin-geolocation" spec="2.4.3">
<variable name="GEOLOCATION_USAGE_DESCRIPTION" value="..." />
</plugin>
package.json
"#ionic-native/geolocation": "4.9.0",
"cordova-plugin-geolocation": "2.4.3",
"cordova-plugin-mauron85-background-geolocation": "2.3.5",
I have access to webservice https://uslugaterytws1test.stat.gov.pl/terytws1.svc with wsdl https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl
Username: TestPubliczny and password: 1234abcd
I try import wsdl and then place 2 components :
object htpr1: THTTPRIO
WSDLLocation = 'https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl'
Service = 'TerytWs1'
Port = 'custom'
HTTPWebNode = htprqrsp1
Converter.Options = [soSendMultiRefObj, soTryAllSchema, soRootRefNodesToBody, soCacheMimeResponse, soUTF8EncodeXML]
Left = 264
Top = 325
end
object htprqrsp1: THTTPReqResp
UserName = 'TestPubliczny'
Password = '1234abcd'
UseUTF8InHeader = True
InvokeOptions = [soIgnoreInvalidCerts, soAutoCheckAccessPointViaUDDI]
WebNodeOptions = []
UDDIOperator = '0'
Left = 296
Top = 376
end
And in .pas file :
var
ten: terytws1.ITerytWs1;
begin
ten := (htpr1 as terytws1.ITerytWs1);
ShowMessage(BoolToStr(ten.CzyZalogowany));
end;
But I get request timeout,where at the same time consuming using app in C# working ok.
In C# provider of webservice sugest to use this code :
try
{
var proxy = new ChannelFactory<ServiceReferenceWCF.ITerytWs1>("custom");
proxy.Credentials.UserName.UserName = TestPubliczny;
proxy.Credentials.UserName.Password = 1234abcd;
var result = proxy.CreateChannel();
var test = result.CzyZalogowany();
}
catch (Exception ex) { }
and
<client>
<endpoint address="https://uslugaterytws1test.stat.gov.pl/terytws1.svc"
binding="customBinding" bindingConfiguration="custom"
contract="ServiceReference1.ITerytWs1" name="custom" />
</client>
<bindings>
<customBinding>
<binding name="custom">
<security defaultAlgorithmSuite="Default"
authenticationMode="UserNameOverTransport"
requireDerivedKeys="true" includeTimestamp="true"
messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruar
y2005WSSecurityPolicy11BasicSecurityProfile10">
<localClientSettings detectReplays="false" />
<localServiceSettings detectReplays="false" />
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10" />
<httpsTransport maxReceivedMessageSize="2147483647"
maxBufferPoolSize="2147483647"/>
</binding>
</customBinding>
</bindings>
and as I write before from C# I consume service without problems
I have a project that checks the network connectivity state like this:
public void GetStatus ()
{
ConnectivityManager oManager;
ConnectivityState eState;
//
oManager = (ConnectivityManager)m_oContext.GetSystemService (Activity.ConnectivityService);
//
if (oManager.ActiveNetworkInfo == null)
Connected = false;
else
Connected = oManager.ActiveNetworkInfo.IsConnected;
//
// Get the current connection state
if (!Connected)
eState = ConnectivityState.NotConnected;
else if (oManager.GetNetworkInfo (ConnectivityType.Mobile).GetState () == NetworkInfo.State.Connected)
eState = ConnectivityState.Roaming;
else if (oManager.GetNetworkInfo (ConnectivityType.Wifi).GetState () == NetworkInfo.State.Connected)
eState = ConnectivityState.WiFi;
else
eState = ConnectivityState.Other;
//
State = eState;
//
if (StatusUpdated != null)
StatusUpdated ();
}
This worked fine when running from Xamarin Studio, but now I've moved my project over to Visual Studio 2012 it doesn't pick up the permission set in the manifest. Here's what I have in the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="MyApp.Android">
<uses-sdk android:targetSdkVersion="10" android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application android:label="My App"></application>
</manifest>
I created the manifest file by going to the properties of the solution and choosing to create it from there, then checked the checkbox for ACCESS_NETWORK_STATE yet still when I run from VS2012 I get an exception saying the device doesn't have the permission. Any help on this? Thanks.
I have scoured the net for days, unsuccessfully just looking for a working example of a YouTube batch request using the C# API. So much of the documentation is out of date.
These tell me what the XML should look like:
https://developers.google.com/gdata/docs/batch
https://developers.google.com/youtube/2.0/developers_guide_protocol_batch_processing
and this is an example with Google Spreadsheets:
https://developers.google.com/google-apps/spreadsheets/#updating_multiple_cells_with_a_batch_request
Though I'm frightfully close time and again, I keep falling short of the mark with that gloriously descriptive GDataRequestException "Execution of request batch failed".
Help!
Finally cracked it!
Now, so you don't have to go through the same blind trial & terror experience I endured:
using Google.GData.Client;
using Google.GData.YouTube;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
...
YouTubeService service = new YouTubeService("YouTube API Client", Properties.Settings.Default.YouTubeDeveloperKey);
const String searchFields = "entry(id,title,link[#rel='alternate'],author(name,yt:userId),media:group(media:category(#label),media:credit,yt:videoid,yt:uploaderId),yt:statistics,yt:rating,gd:rating(#average),gd:comments/gd:feedLink(#countHint))";
String urlBase = String.Format("https://{0}gdata.youtube.com/feeds/api/videos", (testing ? "stage." : ""));
String url = String.Format("{0}?v=2&fields={1}", urlBase, searchFields);
Debug.Print(url);
YouTubeQuery searchQuery = new YouTubeQuery(url);
searchQuery.Query = keyword;
searchQuery.NumberToRetrieve = Properties.Settings.Default.NumVideosToRetrieve;
searchQuery.OrderBy = "relevance";
lblTagStats.Text = "Retrieving Top " + searchQuery.NumberToRetrieve + " Videos...";
YouTubeFeed searchResults = service.Query(searchQuery);
DebugSaveToXml(searchResults, "searchResults");
foreach (YouTubeEntry entry in searchResults.Entries)
{
titles.Add(entry.Title.Text);
if (entry.Statistics != null)
viewCounts.Add(long.Parse(entry.Statistics.ViewCount));
if (entry.Comments != null)
commentCounts.Add(long.Parse(entry.Comments.FeedLink.CountHint.ToString()));
if (entry.Rating != null)
ratings.Add(entry.Rating.Average);
if (entry.YtRating != null)
{
likeCounts.Add(long.Parse(entry.YtRating.NumLikes));
dislikeCounts.Add(long.Parse(entry.YtRating.NumDislikes));
}
videoURLs.Add(new Uri(entry.AlternateUri.ToString()));
uploaders.Add(entry.Authors[0].Name);
foreach (var category in entry.Media.Categories)
if (category.Attributes["label"] != null)
categories.Add(category.Attributes["label"].ToString());
}
lblTagStats.Text = "Retrieving Subscriber Counts...";
AtomFeed batchRequest = new AtomFeed(searchResults);
batchRequest.BatchData = new GDataBatchFeedData();
batchRequest.BatchData.Type = GDataBatchOperationType.query;
foreach (YouTubeEntry entry in searchResults.Entries)
{
AtomEntry batchEntry = searchResults.CreateFeedEntry();
String uploaderId = entry.Media.ChildNodes.Find(x => x.Name == "yt:uploaderId").InnerText;
batchEntry.Id = new AtomId("tag:youtube.com,2008:user:" + uploaderId); //not returned in search, so reconstruct it
batchEntry.BatchData = new GDataBatchEntryData();
urlBase = String.Format("https://{0}gdata.youtube.com/feeds/api/users", (testing ? "stage." : ""));
url = String.Format("{0}/{1}?v=2", urlBase, entry.Media.Credit.Value);
Debug.Print(url);
batchEntry.EditUri = url;
batchRequest.Entries.Add(batchEntry);
}
DebugSaveToXml(batchRequest, "batchRequest_Profiles");
const String profileFields = ""; // "&fields=id,yt:username,yt:statistics(#subscriberCount)"; // YouTube API bug: cant handle colons in batch request fields
urlBase = String.Format("https://{0}gdata.youtube.com/feeds/api/users/batch", (testing ? "stage." : ""));
url = String.Format("{0}?v=2{1}", urlBase, profileFields);
Debug.Print(url);
YouTubeFeed profilesFeed = (YouTubeFeed)service.Batch(batchRequest, new Uri(url));
DebugSaveToXml(profilesFeed,"profilesFeed");
foreach (ProfileEntry entry in profilesFeed.Entries)
if (entry.BatchData.Status.Code == 200)
subscriberCounts.Add(long.Parse(entry.Statistics.SubscriberCount));
lblTagStats.Text = "Retrieving Full Descriptions...";
batchRequest = new AtomFeed(searchResults);
batchRequest.BatchData = new GDataBatchFeedData();
batchRequest.BatchData.Type = GDataBatchOperationType.query;
foreach (YouTubeEntry entry in searchResults.Entries)
{
AtomEntry batchEntry = searchResults.CreateFeedEntry();
batchEntry.Id = entry.Id;
batchEntry.BatchData = new GDataBatchEntryData();
urlBase = String.Format("https://{0}gdata.youtube.com/feeds/api/videos", (testing ? "stage." : ""));
url = String.Format("{0}/{1}?v=2", urlBase, entry.VideoId);
Debug.Print(url);
batchEntry.EditUri = url;
batchRequest.Entries.Add(batchEntry);
}
DebugSaveToXml(batchRequest, "batchRequest_Descriptions");
const String descriptionFields = ""; // "&fields=media:group/media:description"; // YouTube API bug: cant handle colons in batch request fields
urlBase = String.Format("https://{0}gdata.youtube.com/feeds/api/videos/batch", (testing ? "stage.":""));
url = String.Format("{0}?v=2{1}", urlBase, descriptionFields);
Debug.Print(url);
YouTubeFeed descriptionsFeed = (YouTubeFeed)service.Batch(batchRequest, new Uri(url));
DebugSaveToXml(descriptionsFeed,"descriptionsFeed");
foreach (YouTubeEntry entry in descriptionsFeed.Entries)
if (entry.BatchData.Status.Code == 200)
descriptions.Add(entry.Media.Description.Value);
And FYI, this posts the following batch request XML for the profiles, which differs considerably from other samples, but still works like a charm:
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch">
<link rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml" />
<link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" />
<link rel="self" type="application/atom+xml" />
<link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" />
<batch:operation type="query" />
<entry xmlns:gd="http://schemas.google.com/g/2005">
<id>tag:youtube.com,2008:user:UC7UgD2HIyslGofSyX811fsQ</id>
<link href="https://stage.gdata.youtube.com/feeds/api/users/inspiredtennis?v=2" rel="edit" type="application/atom+xml" />
</entry>
<entry xmlns:gd="http://schemas.google.com/g/2005">
<id>tag:youtube.com,2008:user:UClXdxsQW4AqykIq2Fu4YXvQ</id>
<link href="https://stage.gdata.youtube.com/feeds/api/users/azishertanto?v=2" rel="edit" type="application/atom+xml" />
</entry>
<entry xmlns:gd="http://schemas.google.com/g/2005">
<id>tag:youtube.com,2008:user:UC1Diq4duvGuTUaGxk61-LOQ</id>
<link href="https://stage.gdata.youtube.com/feeds/api/users/atamaiidotcom?v=2" rel="edit" type="application/atom+xml" />
</entry>
...
</feed>