HTML5 Audio Mute in Android webview - java

I am using HTML5 audio player inside an android webview. I want to mute the audio and I am using the code like this
this.mute = function()
{
console.debug("Muted");
if(_audioHtml.muted == undefined) {
alert("Doesn't exist");
}
else {
if(_audioHtml.muted === true) {
alert("Muted");
}
else if (_audioHtml.muted === false) {
alert("Non Muted");
}
else {
alert("None of them");
}
}
_audioHtml.muted = true;
};
After each call I can see that the value of muted changes. But its not generating any effect on the device. It always generate the sound in set volume. How can I do this in android. I am using Android 4.0.4.
Thanks.

Assuming an audio tag like <audio id="player" src="something.mp3" />, you should be toggling the muted property of the tag itself using Javascript... something like
$('#player').muted = true;

It works if you set the audio this way: (the html5 tag will be muted)
In your JAVA activity:
wv.loadUrl("file:///android_asset/index.html");
wv.addJavascriptInterface(this, "jInterface");
in your html file:
to mute:
<script>
jInterface.mute();
</script>
now back to your java activity:
public void mute()
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}

I haven't found a solution for my MotoX 4.2 device yet, but this tends to work in most cases, basically you have pause the video once it starts playing
The caveat here is that my Samsung 4.3 device is firing "playing" way too early, it should fire when the video actually starts playing, but it fires when the video starts loading
if (sdkVersion < 4.4) {
player.addEventListener("timeupdate", pauseIfPlaying); // check player.currentTime > 0
} else {
player.addEventListener("playing", function () {
player.muted = true;
});
}

Related

How to play audio using the device's volume?

The Audio interface allows to set its volume, but apps usually use the Media or Notifications volumes on Android. In a Gluon Mobile app, pressing the volume keys does nothing, while in other apps the device's volume changes.
Tested on Android 8 and 12 using Attach version 4.0.15.
Is there a way to play audio using the device's volume settings and allow the user to adjust the volume from within the device?
There seems to be no proper way to do this. Using the VideoService it's possible to change the volume of the device, but only while audio is playing, which requires the user to be ready to do so for short audio clips.
The VideoService also does not support playing a single file out of a playlist. The only solution I found was switching the playlist to a single audio clip whenever it's required to be played and isn't played already:
class MobileNotifier {
private static final String SMALL_BEEP_PATH = "/sounds/SmallBeep.wav";
private static final String BIG_BEEP_PATH = "/sounds/BigBeep.wav";
VideoService service;
private MobileNotifier(VideoService service) {
this.service = service;
service.getPlaylist().add(SHORT_BEEP_PATH);
}
public void play(Alert alert) {
switch (alert) {
case SMALL -> {
if (service.statusProperty().get() != Status.PLAYING || !SMALL_BEEP_PATH.equals(service.getPlaylist().get(0))) {
service.stop();
service.getPlaylist().set(0, SMALL_BEEP_PATH);
service.play();
}
}
case BIG -> {
if (service.statusProperty().get() != Status.PLAYING || !BIG_BEEP_PATH.equals(service.getPlaylist().get(0))) {
service.stop();
service.getPlaylist().set(0, LONG_BEEP_PATH);
service.play();
}
}
};
}
}

How to turn on Front flashlight(not the rear one) of a android device

I developed a simple application to turn ON/OFF flashlight. But I couldn't find a way to turn on front flashlight of a device(if available).
Code for availability check :
boolean hasCameraFlash = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
My code for turn ON is :
#RequiresApi(api = Build.VERSION_CODES.M)
private void flashLightOn() {
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, true);
} catch (CameraAccessException ignored) {
}
}
Is it possible to turn on front flashlight of device without turning on camera.
Any help will be appreciated.
(Please note that I'm a newcomer to android development)

Best approach to Notification Sounds on Web Apps

I have a Delivery System that I made with Laravel + Vue.Js and all is working fine, but I'm facing some problems with Notification Sounds.
When the client makes an order on his cellphone or pc, I need to show a Notification sound alert with a custom sound to admin from the Restaurant.
But when I'm working with Chrome or Mozilla, sometimes my Notification doesn't show up and the custom sound only plays if the admin stays on the web page but not in another tab or minimized.
I want to make this process 100% with the sound and the Notification always showing.
When I see another competitor's software I see that they have a small java desktop application only to do that. I can do some similar with Electron?
But I don't have any idea where to start making some like this or the name is called.
Here is my code for notification on my Web Application, I'm using FCM:
const messaging = firebase.messaging();
navigator.serviceWorker.register("{{url('firebase/sw-js')}}")
.then((registration) => {
messaging.useServiceWorker(registration);
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
getRegToken();
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
var audio = new Audio('urltosound.mp3');
messaging.onMessage((payload) => {
console.log("Message received. ", payload);
notificationTitle = payload.data.title;
notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
image: payload.data.image,
requireInteraction: true,
};
var notification = new Notification(notificationTitle, notificationOptions);
notification.onshow = function() {
audio.play();
audio.loop = true;
};
notification.onclose = function() {
audio.pause();
audio.currentTime = 0;
};
notification.onclick = function() {
audio.pause();
audio.currentTime = 0;
// window.location.href = '/administrativo/orders/' + payload.data.orderid;
window.open('/administrativo/orders/' + payload.data.orderid, '_blank');
};
notification.addEventListener('close', () => {
audio.pause();
audio.currentTime = 0;
});
});
});
It is working but when we are playing with Notification and Custom Sound on a Browser I'm not very confident that always will play and show and this can't happen.

Android NotificationListenerService: how to know if user clicked on the notification (opening the related app) or simply deleted it

I'm working with notifications generated by every app (not only mine) on my Android device (android 5.1.1).
By extending NotificationListenerService I'm able to know when a push notification is posted (overriding the "onNotificationPosted" method) and when a notification is removed (overriding the "onNotificationRemoved" method).
The problem is that I would like to know how the notification was removed:
a) by clicking it (so opening the app)
or
b) by swyping it (so it is only removed)
?
Is it possible to know it?
Thank you in advance!
The best way to do it is to get the list of all running processes!
So, in the onNotificationRemoved method we can:
1. obtain the list of running processes using the Android Processes library
2. compare each process name with the packageName
3. if the comparison return a true value, we check if the process is in foreground
public void onNotificationRemoved(StatusBarNotification sbn) {
String packageName = sbn.getPackageName();
try {
List<AndroidAppProcess> processes = ProcessManager.getRunningAppProcesses();
if (processes != null) {
for (AndroidAppProcess process : processes) {
String processName = process.name;
if (processName.equals(packageName)) {
if (process.foreground ==true)
{
//user clicked on notification
}
else
{
//user swipe notification
}
}
}
}
}
catch (Exception e)
{
String error = e.toString();
}
}

Prompt Android App User to Update App if current version <> market version

Lets say my Android App version 0.1 is installed currently on the User's phone. Everytime they launch my App I want to check if there is a different version available in the Android Market let's say this version is 0.2. If there is a mismatch between these two version I want to show a dialog box prompting the user to Upgrade the App.
I totally understand there exists a notification procedure from Android Market itself to the users but as far as my Analytics data is concerned it is not very effective in reminding users to upgrade to the new version of the App.
Any insight would be very helpful. Thanks StackOverflowers, you guys rock!
As of 2019 the best way for updating your app is to use In-app updates provided by Play Core library (1.5.0+). It works for Lollipop and newer, but let's be fair, Kit-Kat is less than 7% as of today and soon will be gone forever. You can safely run this code on Kit-Kat without version checks, it won't crash.
Official documentation: https://developer.android.com/guide/app-bundle/in-app-updates
There are two types of In-app updates: Flexible and Immediate
Flexible will ask you nicely in a dialog window:
whereas Immediate will require you to update the app in order to continue using it with full-screen message (this page can be dismissed):
Important: for now, you can't choose which type of update to roll out in your App Release section on Developer Play Console. But apparently, they will give us that option soon.
From what I've tested, currently, we're getting both types available in onSuccessListener.
So let's implement both types in our code.
In module build.gradle add the following dependency:
dependencies {
implementation 'com.google.android.play:core:1.6.1'//for new version updater
}
In MainActivity.class:
private static final int REQ_CODE_VERSION_UPDATE = 530;
private AppUpdateManager appUpdateManager;
private InstallStateUpdatedListener installStateUpdatedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkForAppUpdate();
}
#Override
protected void onResume() {
super.onResume();
checkNewAppVersionState();
}
#Override
public void onActivityResult(int requestCode, final int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQ_CODE_VERSION_UPDATE:
if (resultCode != RESULT_OK) { //RESULT_OK / RESULT_CANCELED / RESULT_IN_APP_UPDATE_FAILED
L.d("Update flow failed! Result code: " + resultCode);
// If the update is cancelled or fails,
// you can request to start the update again.
unregisterInstallStateUpdListener();
}
break;
}
}
#Override
protected void onDestroy() {
unregisterInstallStateUpdListener();
super.onDestroy();
}
private void checkForAppUpdate() {
// Creates instance of the manager.
appUpdateManager = AppUpdateManagerFactory.create(AppCustom.getAppContext());
// Returns an intent object that you use to check for an update.
Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
// Create a listener to track request state updates.
installStateUpdatedListener = new InstallStateUpdatedListener() {
#Override
public void onStateUpdate(InstallState installState) {
// Show module progress, log state, or install the update.
if (installState.installStatus() == InstallStatus.DOWNLOADED)
// After the update is downloaded, show a notification
// and request user confirmation to restart the app.
popupSnackbarForCompleteUpdateAndUnregister();
}
};
// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
// Request the update.
if (appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
// Before starting an update, register a listener for updates.
appUpdateManager.registerListener(installStateUpdatedListener);
// Start an update.
startAppUpdateFlexible(appUpdateInfo);
} else if (appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE) ) {
// Start an update.
startAppUpdateImmediate(appUpdateInfo);
}
}
});
}
private void startAppUpdateImmediate(AppUpdateInfo appUpdateInfo) {
try {
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.IMMEDIATE,
// The current activity making the update request.
this,
// Include a request code to later monitor this update request.
MainActivity.REQ_CODE_VERSION_UPDATE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
private void startAppUpdateFlexible(AppUpdateInfo appUpdateInfo) {
try {
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.FLEXIBLE,
// The current activity making the update request.
this,
// Include a request code to later monitor this update request.
MainActivity.REQ_CODE_VERSION_UPDATE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
unregisterInstallStateUpdListener();
}
}
/**
* Displays the snackbar notification and call to action.
* Needed only for Flexible app update
*/
private void popupSnackbarForCompleteUpdateAndUnregister() {
Snackbar snackbar =
Snackbar.make(drawerLayout, getString(R.string.update_downloaded), Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.restart, new View.OnClickListener() {
#Override
public void onClick(View view) {
appUpdateManager.completeUpdate();
}
});
snackbar.setActionTextColor(getResources().getColor(R.color.action_color));
snackbar.show();
unregisterInstallStateUpdListener();
}
/**
* Checks that the update is not stalled during 'onResume()'.
* However, you should execute this check at all app entry points.
*/
private void checkNewAppVersionState() {
appUpdateManager
.getAppUpdateInfo()
.addOnSuccessListener(
appUpdateInfo -> {
//FLEXIBLE:
// If the update is downloaded but not installed,
// notify the user to complete the update.
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
popupSnackbarForCompleteUpdateAndUnregister();
}
//IMMEDIATE:
if (appUpdateInfo.updateAvailability()
== UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
// If an in-app update is already running, resume the update.
startAppUpdateImmediate(appUpdateInfo);
}
});
}
/**
* Needed only for FLEXIBLE update
*/
private void unregisterInstallStateUpdListener() {
if (appUpdateManager != null && installStateUpdatedListener != null)
appUpdateManager.unregisterListener(installStateUpdatedListener);
}
And we're done!
Testing.
Please read the docs so you will know how to test it properly with test tracks on Google Play.
Long story short:
Sign your app with the release certificate and upload it to the one of publishing tracks in Developer Play Console under App Releases (alpha/beta/other custom closed track).
In your release track page in the Manage Testers section create and add a list of testers and make sure you checked the checkbox! - this step is optional since your developer account email is also a testers account and you can use it for testing.
Under the list of testers you will find "Opt-in URL" - copy this url and give it to your testers or open it yourself. Go to that page and accept proposition for testing. There will be a link to the app. (You won't be able to search for the app in Play Store so bookmark it)
Install the app on your device by that link.
In build.gradle increment the version of defaultConfig { versionCode k+1 } and build another signed apk Build > Generate Signed Bundle / APK... and upload it to your publishing track.
Wait for... 1 hour? 2 hours? or more before it will be published on the track.
CLEAR THE CACHE of Play Store app on your device. The problem is that Play app caches details about installed apps and their available updates so you need to clear the cache. In order to do that take two steps:
7.1. Go to Settings > App > Google PLay Store > Storage > Clear Cache.
7.2. Open the Play Store app > open main menu > My apps & games > and there you should see that your app has a new update.
If you don't see it make sure that your new update is already released on the track (go to your bookmarked page and use it to open your apps listing on the Play Store to see what version is shown there). Also, when your update will be live you'll see a notification on the top right of your Developer Play Console (a bell icon will have a red dot).
Hope it helps.
The Android Market is a closed system and has only an unofficial api that might break at any point of time.
Your best bet is simply to host a file(xml, json or simple text) on a web server of yours in which you just have to update the current version of your app when you post it on the Market.
Your app will then only have to fetch that file at startup, checks wether currently installed app has a lower version number and displays a dialog to warn the user he is lagging.
Another option you can use, if you want to avoid having your backend server to store your current app version like it's suggested in the accepted answer, is to use Google Tag Manager (GTM).
If you're already using the Google Analytics SDK, you have the GTM in it also.
In GTM you can define a value in the container for your app that specifies your latest released version. For example:
{
"latestAppVersion": 14,
...
}
Then you can query that value when your app starts and show the user update dialog reminder if there's a newer version.
Container container = TagManager.getInstance(context).openContainer(myContainerId);
long latestVersionCode = container.getLong("latestAppVersion");
// get currently running app version code
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
long versionCode = pInfo.versionCode;
// check if update is needed
if(versionCode < latestVersionCode) {
// remind user to update his version
}
Take a look at this library that you can use to query the Android Market API
http://code.google.com/p/android-market-api/
You can use this Android Library: https://github.com/danielemaddaluno/Android-Update-Checker. It aims to provide a reusable instrument to check asynchronously if exists any newer released update of your app on the Store.
It is based on the use of Jsoup (http://jsoup.org/) to test if a new update really exists parsing the app page on the Google Play Store:
private boolean web_update(){
try {
String curVersion = applicationContext.getPackageManager().getPackageInfo(package_name, 0).versionName;
String newVersion = curVersion;
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + package_name + "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
return (value(curVersion) < value(newVersion)) ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
And as "value" function the following (works if values are beetween 0-99):
private long value(String string) {
string = string.trim();
if( string.contains( "." )){
final int index = string.lastIndexOf( "." );
return value( string.substring( 0, index ))* 100 + value( string.substring( index + 1 ));
}
else {
return Long.valueOf( string );
}
}
If you want only to verify a mismatch beetween versions, you can change:
"value(curVersion) < value(newVersion)" with "value(curVersion) != value(newVersion)"
For prompting Android App User to Update App if current version is not equal to market version, you should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941
My working Kotlin code for force App update:
const val FLEXIABLE_UPADTE: Int = 101
const val FORCE_UPDATE: Int = 102
const val APP_UPDATE_CODE: Int = 500
override fun onCreate {
// Get updateType from Webservice.
updateApp(updateType)
}
private fun updateApp(statusCode: Int) {
appUpdateManager = AppUpdateManagerFactory.create(this #MainActivity)
val appUpdateInfoTask = appUpdateManager ? .appUpdateInfo
appUpdateInfoTask ? .addOnSuccessListener {
appUpdateInfo - >
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
if ((statusCode == Constants.FORCE_UPDATE))
appUpdateManager ? .startUpdateFlowForResult(
appUpdateInfo, AppUpdateType.IMMEDIATE, this, Constants.APP_UPDATE_CODE
)
else if (statusCode == Constants.FLEXIABLE_UPADTE)
appUpdateManager ? .startUpdateFlowForResult(
appUpdateInfo, AppUpdateType.FLEXIBLE, this, Constants.FLEXIABLE_UPADTE
)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent ? ) {
try {
if (requestCode == Constants.APP_UPDATE_CODE && resultCode == Activity.RESULT_OK) {
if (resultCode != RESULT_OK) {
appUpdateCompleted()
}
}
} catch (e: java.lang.Exception) {
}
}
private fun appUpdateCompleted() {
Snackbar.make(
findViewById(R.id.activity_main_layout),
"An update has just been downloaded.",
Snackbar.LENGTH_INDEFINITE
).apply {
setAction("RESTART") {
appUpdateManager.completeUpdate()
}
setActionTextColor(resources.getColor(R.color.snackbar_action_text_color))
show()
}
}

Categories

Resources