HTML5 navigator.online does not work in WebView - android

I am creating a hybrid application by using android and offline html5 pages in android asset.
navigator.online is not working in Android Webview.
Please help

If anyone is still searching for this one. The solution for me was to register a broadcast receiver in my activity to detect connection change.
#Override
protected void onPause() {
super.onPause();
if (connectivityChangeReceiver!=null) unregisterReceiver(connectivityChangeReceiver);
}
#Override
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver,intentFilter);
}
private BroadcastReceiver connectivityChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent)
{
mWebView.setNetworkAvailable(isNetworkAvailable(context));
}
};

Make sure that you provide below permissions in the AndroidMenifest.xml file:
<uses-permission android:name="android.permission.INTERNET />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

you might want to add the following line of code for your events
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
make sure you check the values in the functions function onOnline(){} & function onOffline(){}

Are you sure you are not mistaking the spelling?
it should be navigator.onLine (camelCase)

Webview is partially supported. Please check browser compatibility in the documentation: documentation link

Related

Blazor MAUI - Camera and Microphone Android permissions

I am trying to show live stream from camera & microphone in <video> html element.
In blazor file (sample.razor) I invoke method to request and show video:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("requestMediaAndShow");
}
}
In javascript file (sample.js) I request stream and assign to video html element.
// Create request options
let options = {
audio: true,
video: true
};
// Request user media
navigator.mediaDevices
.getUserMedia(options)
.then(gotLocalStream)
.catch(logError);
But when I am requesting i catch an error like "NotAllowedError: Permission denied".
AndroidManifest.xml contains:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
MainActivity.cs contains:
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.Camera, Manifest.Permission.RecordAudio, Manifest.Permission.ModifyAudioSettings }, 0);
}
}
Any ideas how to request audio and video stream by javascript in BlazorWebView natively on android?
PS. On both on website and natively on Windows platform works great and no extra permissions are required.
Although the Android permissions seem to be granted OK, I suspected the website permissions were not. Not sure if the author of this question is the same person, but an issue was opened on the .NET MAUI repo as well about this.
While we are looking into making this work out of the box, another helpful user has posted this workaround for now.
Implement your own handler like so
public class MauiWebChromeClient : WebChromeClient
{
public override void OnPermissionRequest(PermissionRequest request)
{
request.Grant(request.GetResources());
}
}
public class MauiBlazorWebViewHandler : BlazorWebViewHandler
{
protected override WebChromeClient GetWebChromeClient()
{
return new MauiWebChromeClient();
}
}
And register this handler in your MauiProgram.cs:
builder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<IBlazorWebView, MauiBlazorWebViewHandler>();
});
This will automatically grant all the requested permissions from the web side of things.
I think you are missing some parts of the permission checks. You should read this section about runtime permissions that were introduced in Android 6.0. For example, I cannot see any override of OnRequestPermissionsResult in MainActivity.
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/permissions?tabs=macos#runtime-permission-checks-in-android-60

Android : DbxAccountManager.hasLinkedAccount() always return false on Remote Service

On my Activity :
public class MainActivity extends Activity {
private mDbxAccountManager mDbxAccountManager = null;
...
#Override
public void onCreate(Bundle savedInstanceState) {
...
mDbxAccountManager = DbxAccountManager.getInstance(getApplicationContext(), getString(R.string.dbx_app_key), getString(R.string.dbx_app_secret));
...
}
...
public void buttonOnClick(View view) {
if(mDbxAccountManager.hasLinkedAccount()) {
//Do something
}
else {
mDbxAccountManager.startLink(this, 0);
}
...
}
}
And on my Remote Service :
public class CloudService extends Service {
private mDbxAccountManager mDbxAccountManager = null;
#Override
public void onCreate() {
...
mDbxAccountManager = DbxAccountManager.getInstance(getApplicationContext(), getString(R.string.dbx_app_key), getString(R.string.dbx_app_secret));
if(!mDbxAccountManager.hasLinkedAccount()) {
return;
stopSelf();
}
...
}
}
The result is, after I link my app with dropbox using installed dropbox client, the hasLinkedAccount() on my Activity return true, meanwhile the same code on my Remote Service always return false.
I also check the logcat and it showed that my app already linked with dropbox.
My suspect is that the dropbox API create some SharedPreferences when it successfully link with my app, but my Remote Service can't access that or get a cached version of that SharedPreferences... I don't know...
Please help...
Thank you
Edited :
If I reinstall the app, then the result is as expected and hasLinkedAccount() return true, but if I uninstall and install again which cause clearing the user-data, then I link my app again with Dropbox, then the same strange behaviour appear again.
What I'm doing wrong? I'm turning my head almost 24-hours....
Solved!!!
After trying and trying...
I get conclusion that the Service that runs before the app linked with dropbox will always get DbxAccountManager.hasLinkedAccount() return false.
I try to kill the process by calling Process.killProcess(myservicePid) after I link my app with Dropbox and start the service again and it work.
So... I solved it by not starting the service before the app was linked with dropbox and start the service only if it already linked, because stopSelf() on the service doesn't kill the process.
I think this issue have something to do with the Context getApplicationContext() which is passed to DbxAccountManager.getInstance(), and I don't know why looks like the Context is not updated when the dropbox was link with the app.
Thank you.

Android - Listening to NFC Adapter State Changed

I am trying to build an application which uses NFC. The goal is to display a DialogFragment containing a button link to go the settings and change it manually and when the feature is enabled, disable the DialogFragment.
Problem: If the user enables/disables NFC using the icon in the pull down notifications tray , then the onPause/onResume doesn't get called and misses the condition entirely.
I am sure there is a receiver that I can register to instead and respond appropriately in real time. Any ideas, thoughts or reference will be greatly appreciated!
The following code checks if the state is enabled/disabled. I am also responding to it appropriately in the onResume event.
NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if(adapter != null && adapter.isEnabled()) {
detector = new NfcDetector(this);
detector.setListener(this);
onNfcFeatureFound();
}
else {
onNfcFeatureNotFound();
}
For others looking at this post, the code below will take the user directly into settings to enable/disable NFC:
startActivity(new Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
Thought I should post the answer for other people looking for the same problem, since I wasn't able to find one easily.
Add the following code to your activities onCreate() method:
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
this.registerReceiver(mReceiver, filter);
Inner private class declared within your activity (or anywhere else you like):
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
final int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
NfcAdapter.STATE_OFF);
switch (state) {
case NfcAdapter.STATE_OFF:
break;
case NfcAdapter.STATE_TURNING_OFF:
break;
case NfcAdapter.STATE_ON:
break;
case NfcAdapter.STATE_TURNING_ON:
break;
}
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
// Remove the broadcast listener
this.unregisterReceiver(mReceiver);
}
// The following check needs to also be added to the onResume
#Override
protected void onResume()
super.onResume();
// Check for available NFC Adapter
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
if(adapter != null && adapter.isEnabled()) {
createNfcDetector();
//NFC is available on device, but disabled
}
else {
//NFC Is available and enabled
}
}
You can use ACTION_ADAPTER_STATE_CHANGED to receive a broadcast message when the state of the adapter changes, but that option is only available in API 18 and above. See this for the documentation.
For prior to 18, I don't know of a way to do this unfortunately.
Also, as an aside, the android.provider.Settings.ACTION_NFC_SETTINGS will work on API levels 16 and above. For prior versions, the NFC settings are under "wireless settings". Take a look at the ensureSensorIsOn method at the bottom of this blog post for a code sample that checks against the API level and redirects to the correct settings pane.

Open link on Button

i'm still new and totally noob so please carry on with me .
how to open a link when button clicked in android?
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
Edit: i'm using phonegap plugin . thanks
Write this code inside onClick :
Uri uri = Uri.parse("http://www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
Also add the following line to your manifest.xml because you need to have Internet permission to actually use the internet :
<uses-permission android:name="android.permission.INTERNET" />
Read more about Android Permissions.
To read more about Uri refer this link. Also read how Intents work in Android.
Since you are using PhoneGap, un-comment either of the methods below:
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//super.loadUrl("www.google.com");
// or
//loadUril("www.google.com");
}
});

code to turn the wifi on/off and code to change to silent mode

i'm new to android , i want to program an application for android,
i need some help
i want a way to simply call a function that turn the wifi on/off
and another function that change the profile from silent to general(vibration/ringing)
and from general to silent(ringing/vibration)
any help please???
public class Control{
public void turnVibrationOn(){
.......
}
public void turnVibrationOff(){
.......
}
public void turnWifiOn(){
.......
}
public void turnWifiOff(){
.......
}
}
}
Vibration: Use the AudioManager service.
((AudioManager) getSystemService(AUDIO_SERVICE))
.setRingerMode(AudioManager.RINGER_MODE_VIBRATE)
Wi-Fi: Use the WifiManager service.
((WifiManager) getSystemService(WIFI_SERVICE))
.setWifiEnabled(false)
(And request the proper permission.)

Categories

Resources