android.permission.ACCESS_NETWORK_STATE not recognised - xamarin.android

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.

Related

How to get a list of names of Wi-Fi network

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

Codename One app not provide real location

in out app we have a module where you can send time records with GPS location.
In 40% of cases we have location problem because the module provides a location which is not real (sometime about 1 km away).
When we have this cases we open Google Maps app and it give us perfect location, then again out app and not-real location.
For getting the location we use this:
Slider s1 = new Slider();
Dialog dlg = makeDialog("HIGH PRECISION LOCATION...", s1, null, 'a');
dlg.addShowListener((ActionListener) e -> {
LocationManager locationManager = LocationManager.getLocationManager();
locationManager.setLocationListener(this, new LocationRequest(LocationRequest.PRIORITY_HIGH_ACCUARCY, 500));
loc = locationManager.getCurrentLocationSync(20000);
dlg.dispose();
if(loc == null) {
Slider s2 = new Slider();
Dialog dlg2 = makeDialog("GETTING LAST KNOWN LOCATION...", s2, "OK", 'a');
dlg2.addShowListener((ActionListener) e2 -> {
loc = locationManager.getLastKnownLocation();
if(loc == null) {
// location not found
Dialog.show("Attenzione!", "Posizione non trovata. E' consigliato di spostarsi all'aperto. "
+ "Tuttavia รจ possibile inviare la timbratura anche senza coordinate.", "Ok", null);
} else {
paintLocation(loc, GPSStateOn);
}
});
dlg2.show();
} else {
paintLocation(loc, GPSStateOn);
}
});
dlg.show();
-
#Override
public void locationUpdated(final Location location) {
switch (LocationManager.getLocationManager().getStatus()) {
case LocationManager.AVAILABLE:
GPSStateOn = true;
break;
case LocationManager.OUT_OF_SERVICE:
GPSStateOn = false;
break;
case LocationManager.TEMPORARILY_UNAVAILABLE:
GPSStateOn = false;
break;
}
if(loc != null) {
paintLocation(loc,GPSStateOn);
System.out.println("-----LATITUDINE: " + loc.getLatitude());
System.out.println("-----LONGITUDINE: " + loc.getLongitude());
}
}
We also have added the buil hint android.playService.location = true
ADDED 25/04/2020 11:58
I forgot to say that about 40% of cases it arrives at "GETTING LAST KNOWN LOCATION..." and then give perfect real location.
Android build hints:
last one is cutted... value is:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/><uses-feature android:glEsVersion="0x00020000" android:required="true"/><uses-permission android:name="android.permission.CAMERA"/><uses-feature android:name="android.hardware.camera" android:required="false"/>
ADDED 06/05/2020 10:48
Maybe this can be useful:
I noticed when the location takes a lot the GPS icon isn't displayed in the topbar
And when it takes less time the GPS icon is visible
Looking again at the code I noticed you used set location listener and getCurrentLocationSync which are mutually exclusive in this case. You need to pick one. If you give the former (which is the preferred way) enough time to work it should give you an accurate location. Notice the GPS position sometimes needs a couple of seconds for the initial reading.

PhoneStateListerner GsmCellLocation

I'm running an Android 5.1 project recently. And while LTE testing, I found a weird issue.
I want to get the Cid and Lac by using GsmCellLocation and PhoneStateListener
Here is my code of PhoneStateListener and GsmCellLocation:
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(new PhoneStateListener() {
#Override
public void onCellLocationChanged(CellLocation location) {
String txt = "";
if (location instanceof GsmCellLocation) {
if (location != null) {
//something process when location changed
GsmCellLocation l = (GsmCellLocation) location;
if (l_ != null) {
txt += "\ngetCellLocation: " + l_.getCid();
}
else {
txt += "\ngetCellLocation, location is null";
}
}
}
}
}, PhoneStateListener.LISTEN_CELL_LOCATION);
GsmCellLocation l_ = (GsmCellLocation) mTm.getCellLocation();
String txt = "";
if (l_ != null) {
txt = "getCellLocation: " + l_.getCid();
}
else {
txt = "getCellLocation, location is null";
}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I try to get the location via LTE by using PhoneStateListener in my code.
But It was not working as expected. However, 4G mobile data is working fine.
Only using GsmCellLocation is working fine. I can get the Cid and Lac from GsmCellLocation class.
After tracing the source code, I found that onCellLocationChanged of PhoneStateListener and getCellLocation of GsmCellLocation are running the same function named newFromBundle.
When running getCellLocation I saw this function is working fine with GsmCellLocation(bundle) of newFromBundle so that I can get the proper Cid and Lac by using GsmCellLocation class.
But onCellLocationChanged of PhoneStateListener is always return null with newFromBundle.
public static CellLocation newFromBundle(Bundle bundle) {
// TelephonyManager.getDefault().getCurrentPhoneType() handles the case when
// ITelephony interface is not up yet.
//switch(TelephonyManager.getDefault().getCurrentPhoneType()) {
switch(bundle.getInt("type", PhoneConstants.PHONE_TYPE_NONE)) {
case PhoneConstants.PHONE_TYPE_CDMA:
Log.e(TAG, "create CdmaCellLocation");
return new CdmaCellLocation(bundle);
case PhoneConstants.PHONE_TYPE_GSM:
Log.e(TAG, "create GsmCellLocation");
return new GsmCellLocation(bundle);
default:
return null;
}
}
It doesn't make sense. Why do I say that. I got three SIMs of South Korea, KT, LG U+ and SK Telecom.
These three SIMs are working fine with getCellLocation of GsmCellLocation.
KT and SK Telecom are working fine with onCellLocationChanged of PhoneStateListener.
Only LG U+ is malfunction by using onCellLocationChanged of PhoneStateListener.
I don't think my code is wrong. However, the vendor of the unit said I have to setup proper SubId to let PhoneStateListener initialized.
I'm a little confused about it. I don't have to set any SubId when using SK and SK Telecom, but why do Lg U+ need to do that? And after I set the SubId of LG U+, it still doesn't work.
Is there anyone meet the issue? This issue has already perplexed me for a long time.

app.config Xamarin pcl

I need to add some tag in a app.config file for implement a dll (xmlsoccer).
I have to add something like
<system.serviceModel>
<bindings>
<basicHttpBinding>
in a configuration node, but I don't know where it is.
I tried to create an app.config file and set DotNetConfig.xsd as scheme, but during compile, I have this errors:
WARNING: failed to load endpoint configuration for *
SyStem.InvalidOperationException: A Binding must be configured for this channel factory
can anyone help me?
I tried to write this:
` public class MainActivity : FormsApplicationActivity
{
public static readonly EndpointAddress EndPoint = new EndpointAddress("http://www.xmlsoccer.com/FootballDataDemo.asmx");
App application;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
// LoadApplication(new App(binding, EndPoint));
CreateBasicHttp();
LoadApplication(application);
}
private void CreateBasicHttp()
{
var binding = new BasicHttpBinding()
{
Name = "basicHttpBinding",
MaxReceivedMessageSize = 1000000,
};
binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
{
MaxArrayLength = 2147483646,
MaxStringContentLength = 5242880,
};
var timeout = new TimeSpan(0, 1, 0);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
application = new App(binding, new EndpointAddress("http://www.xmlsoccer.com/FootballDataDemo.asmx"));
}`
in my MainActivity.cs, but obviously it isn't enough.
Still looking for answer?
Take a look here:
https://forums.xamarin.com/discussion/19303/how-to-consume-wcf-service-in-xamarin-forms-pcl
Steps:
1.- Opening a command prompt in Windows and using the SLSvcUtil.exe tool
from the Silverlight SDK to generate a proxy from a WSDL file. slsvcutil http://www.yourserver.com/WebServices/YourServiceSoapClient.asmx?WSDL /out:YourService.cs That utility is located at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v5.0\Tools\ on my computer.
2.- Adding the resulting YourService.cs file to my project.
3.- Adding the following code to access the service:
// Create the WCF client (created using SLSvcUtil.exe on Windows)
YourServiceSoapClient client = new YourServiceSoapClient(
new BasicHttpBinding(),
new EndpointAddress("hhttp://www.yourserver.com/WebServices/YourServiceSoapClient.asmx"));
// Call the proxy - this should use the async versions
client.ServiceFunctionCompleted += OnGotResult;
client.ServiceFunctionAsync(parameter);
And the OnGotResult function:
void OnGotResult(object sender, ServiceFunctionCompletedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () => {
string error = null;
if (e.Error != null)
error = e.Error.Message;
else if (e.Cancelled)
error = "Cancelled";
if (!string.IsNullOrEmpty(error))
{
await DisplayAlert("Error", error, "OK", "Cancel");
}
else
{
resultsLabel.Text = e.Result;
}
});
}

Inability to display image after deployment to Azure server but works in localhost

I am having difficulty displaying images after deploying to Azure.
I am currently developing my application on ASP.NET MVC 5.
My methodology is for admin to upload a particular image, which would be accessible by users. The image is to be uploaded into a folder.
The issue is that I am able to get the image upload and displaying to work in my own localhost. However, it failed to work when I publish my app to Azure.
I have tried with many of the suggestions found in stackoverflow.
E.g. Changing the Permission settings in the folder, but up to no avail.
I have attached my code for reference. I appreciate any help! =D
Controller (file upload):
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/ExerciseImagesDepository"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ExerciseImage eI = new ExerciseImage();
eI.ExerciseID = ex.ExerciseID;
eI.ImageURL = Path.GetFileName(file.FileName);
db.ExerciseImages.Add(eI);
db.SaveChanges();
}
catch (Exception exc)
{
ViewBag.FileUploadErrorMessage = "ERROR:" + exc.Message.ToString();
}
Controller (Details display)
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
List<ExerciseViewModel> evmLIst = new List<ExerciseViewModel>();
int a = 0;
List<Exercise> exercise = db.Exercises.ToList();
foreach (var item in exercise)
{
ExerciseViewModel evm = new ExerciseViewModel();
a = a + 1;
evm.ExerciseViewModelID = a;
evm.ExerciseRegion = db.ExerciseRegions.Find(item.ExerciseRegionID);
evm.ExerciseDescription = item.Description;
evm.ExerciseType = db.ExerciseTypes.Find(item.ExerciseTypeID);
int ExerciseID = item.ExerciseID;
ExerciseVideo ev = db.ExerciseVideos.Where(m => m.ExerciseID == ExerciseID).SingleOrDefault();
evm.VideoURL = ev.VideoURL;
ExerciseImage ei = db.ExerciseImages.Where(m => m.ExerciseID == id).SingleOrDefault();
if (ei != null)
{
evm.ImageURL = ei.ImageURL;
}
else
{
evm.ImageURL = "No Image Is Available For This Exercise";
}
evm.Exercise = item.Name;
evmLIst.Add(evm);
}
View
<div>
<p> TESTING HERE #Html.Raw(Model.ImageURL) </p>
<img src="~/ExerciseImagesDepository/#Html.Raw(Model.ImageURL)"/>
Folder Structure:
I solve it! I figured that perhaps folder that are not default in the MVC 5 framework might be causing the issue. So instead, I created a new folder within the content directory and added a folder inside. Next, I tried changing that particular folder permission settings by adding a group or usernames "IUSR" and allowing full control. I then published the particular folder specifically to Azure and it works. Although I have no idea why I manage to do it.

Resources