So i want to implement a interstitial ad into my app. I am starting testing with the test ads and they don't work. I get error code 3 from onAdFailedToLoad() method.Also i've tried showing an interstitial from this example and it didn't work aswell https://github.com/googleads/googleads-mobile-android-examples. I tried to run it from a nougat os btw
Here is my code:
The setupAds()method is called in onCreate()
private void setupAds() {
//MobileAds.initialize(this, "AD_ID");
MobileAds.initialize(this,
"AD_ID");
mInterstitial=new InterstitialAd(this);
mInterstitial.setAdUnitId("AD_ID");
mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Toast.makeText(PopupActivity.this, "onAdlOOADED", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(PopupActivity.this, "onAdfailedtoload" + errorCode, Toast.LENGTH_SHORT).show();
}
#Override
public void onAdOpened() {
Toast.makeText(PopupActivity.this, "onAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLeftApplication() {
Toast.makeText(PopupActivity.this, "onAdleftaplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdClosed() {
Toast.makeText(PopupActivity.this, "onAdcLOASED", Toast.LENGTH_SHORT).show();
}
});
AdRequest request = new AdRequest.Builder().
addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mInterstitial.loadAd(request);
((Button) mView.findViewById(R.id.test_ad_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitial.isLoaded()){
mInterstitial.show();
}
}
});
}
And i show the ad here :
if (!isFirstStarted()){
if (mInterstitial.isLoaded()){
mInterstitial.show();
}
}
And here is a snippet of the manifest:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher_round"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ID"/>
This code works for me !
Note : In this example i used testing ads id and testing interstitial id.
MobileAds.initialize(LoginActivity.this, "ca-app-pub-3940256099942544~3347511713");
mInterstitialAd = new InterstitialAd(LoginActivity.this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build());
mInterstitialAd.setAdListener(new com.google.android.gms.ads.AdListener() {
#Override
public void onAdLoaded() {
mInterstitialAd.show();
super.onAdLoaded();
}
});
Check this Link .
ERROR_CODE_NO_FILL : The ad request was successful, but no ad was returned due to lack of ad inventory.
The errorCode 3 means that AdMob cannot fulfill your AD request.
According to the document of onAdFailedToLoad() method, there are 4 types of error.
errorCode 0: ERROR_CODE_INTERNAL_ERROR - Something happened internally; for instance, an invalid response was received from the ad server.
errorCode 1: ERROR_CODE_INVALID_REQUEST - The ad request was invalid; for instance, the ad unit ID was incorrect.
errorCode 2: ERROR_CODE_NETWORK_ERROR - The ad request was unsuccessful due to network connectivity.
errorCode 3: ERROR_CODE_NO_FILL - The ad request was successful, but no ad was returned due to lack of ad inventory. According to the AdMob Help Community, a policy violation also leads to errorCode 3.
Case 1 only happens by a careless developer. It should not happen. It is not user trigger-able.
Case 2 occurs when a user uses an AD-blocker or network connection is down. It is user trigger-able.
Case 0, case 2 and case 3 are not controllable by developers. I suggest that you need to deal with these cases in your app.
Related
I am developing an App Locker for android. Everything works except for when you try to delete an app, the popup does not appear. I tried to force the lock-screen dialog to appear manually from within the app, but the results were crashes and ANRs.
I thought to myself that the popup is not available because the packageInstaller (System app) is using the screen at the same time, and it gets more priority.
Another thing is that when I cancel an uninstall, packageInstaller goes away and then my display appears for a fraction of a second and then disappears. Note that this is after, I need it to be present before, or even while the packageInstaller is running.
My question is if it is possible to put my window at a certain priority, so that goes even above the system app?
In my app check service, in my method that's on repeat constantly I had:
`
if (mpackageName.equals("com.google.android.packageinstaller")) {
showUnlockDialog();
}
however, this caused my lock-display to get opened a lot of times (because of the repeat), which caused the app to become irresponsive. What I now have (after omitting) is the dialog appearing after, at the end then going away on its own.
This is my show dialog method:
`
{
if (context == null) {
context = getApplicationContext();
}
LayoutInflater layoutInflater = LayoutInflater.from(context);
#SuppressLint("InflateParams") View promptsView;
promptsView = layoutInflater.inflate(R.layout.popup_unlock, null, false);
Lock9View lock9View = (Lock9View) promptsView.findViewById(R.id.lock_9_view);
Button forgetPassword = (Button) promptsView.findViewById(R.id.forgetPassword);
LinearLayout linearLayout = promptsView.findViewById(R.id.popup_background);
TextView textView = promptsView.findViewById(R.id.textView);
linearLayout.setBackgroundResource(R.drawable.gradient_list);
textView.setTextColor(getResources().getColor(R.color.colorWhite));
forgetPassword.setTextColor(getResources().getColor(R.color.colorWhite));
animateBanner1(linearLayout);
lock9View = (Lock9View) promptsView.findViewById(R.id.lock_10_view);
lock9View.setVisibility(View.VISIBLE);
lock9View.setCallBack(new Lock9View.CallBack() {
#Override
public void onFinish(String password) {
if (password.matches(sharedPreference.getPassword(context))) {
dialog.dismiss();
} else {
Toast.makeText(context, "Wrong pattern, try again", Toast.LENGTH_SHORT).show();
}
}
});
forgetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AppCheckServices.this, PasswordRecoveryActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
dialog.dismiss();
}
});
dialog = new Dialog(context, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}
else {
Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_PHONE);
}
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
dialog.setContentView(promptsView);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_UP) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
return true;
}
});
}
dialog.show();
}
As I said this works on every other app besides the packageInstaller even if I specifically lock it.
Here are my relevant Manifest Permissions:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission
android:name="android.permission.INTERNAL_SYSTEM_WINDOW"
tools:ignore="ProtectedPermissions" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
From What I understand, the highest "setType()" for the window manager is the:
SYSTEM_ALERT_WINDOW
It allows to have the top most display. I thought that by using this, I could block the packageInstaller.
However this too requires special permission (2003 from the crashes), and does not get granted easily.
I would appreciate any help in regard to this matter and can post anything else that is relevant.
Thanks in advance!
`
I've spent days (well, nights) trying to work this out. So many examples online are for different versions of Android Studio, different versions of Android, different versions of OpenCV and I can't get any of them to the final 'working' stage.
This example (based on a youtube tutorial, I got to the point where I needed permissions. That's fine, I added that in and a check for them, and it pops up asking the user for camera permissions. But the screen stays blank. I've put in logcat debug, all the right methods seem to be getting called. Would appreciate any assistance.
Code:
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mytestopencvapp" >
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.mytestopencvapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCamera2View;
import org.opencv.android.JavaCameraView;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
private static String TAG = "MainActivity";
JavaCameraView javaCameraView;
Mat mRGBA, mRGBAT;
private final int PERMISSIONS_READ_CAMERA=1;
BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(MainActivity.this) {
#Override
public void onManagerConnected(int status) {
Log.d(TAG, "callbacksuccess");
switch (status)
{
case BaseLoaderCallback.SUCCESS:
{
Log.d(TAG, "case success");
javaCameraView.enableView();
break;
}
default:
{
Log.d(TAG, "case default");
super.onManagerConnected(status);
break;
}
}
}
};
static
{
if (OpenCVLoader.initDebug())
{
Log.d(TAG, "OpenCV is intialised");
}
else
{
Log.d(TAG, "OpenCV is not initialised");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_main);
javaCameraView = (JavaCameraView)findViewById(R.id.my_camera_view);
javaCameraView.setVisibility(SurfaceView.VISIBLE);
javaCameraView.setCvCameraViewListener(MainActivity.this);
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
PERMISSIONS_READ_CAMERA);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
Log.d(TAG, "PERMISSIOns granted");
// Permission has already been granted
}
}
#Override
public void onCameraViewStarted(int width, int height) {
Log.d(TAG, "onCameraViewStarted");
mRGBA = new Mat(height, width, CvType.CV_8UC4);
}
#Override
public void onCameraViewStopped() {
Log.d(TAG, "onCameraViewStopped");
mRGBA.release();
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
{
Log.d(TAG, "onCameraFrame");
/* mRGBA = inputFrame.rgba();
mRGBAT = mRGBA.t();
Core.flip(mRGBA.t(), mRGBAT, 1);
Imgproc.resize(mRGBAT, mRGBAT, mRGBA.size());
return mRGBAT;*/
mRGBA = inputFrame.rgba();
Core.transpose(mRGBA, mRGBAT);
Imgproc.resize(mRGBAT, mRGBAT, mRGBAT.size(),0,0,0);
Core.flip(mRGBA.t(), mRGBA, 1);
return mRGBA;
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
if (javaCameraView != null)
{
javaCameraView.disableView();
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
if (javaCameraView != null)
{
javaCameraView.disableView();
}
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (OpenCVLoader.initDebug())
{
Log.d(TAG, "OpenCV is intialised again");
baseLoaderCallback.onManagerConnected((BaseLoaderCallback.SUCCESS));
}
else
{
Log.d(TAG, "OpenCV is not working");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, this, baseLoaderCallback);
}
}
}
And my res layout activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<org.opencv.android.JavaCameraView
android:id="#+id/my_camera_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
As far as I can tell, I've linked them all correctly, I can confirm OpenCV initialises, permissions are checked and granted, but then...the JavaCameraView is just black.
You need to tell the CameraView that the camera permission was granted. You can do so by calling the setCameraPermissionGranted() function. This function call should go into the 'permission granted' block in your onCreate method as shown below:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// More code here ...
} else {
Log.d(TAG, "Permissions granted");
javaCameraView.setCameraPermissionGranted();
}
In addition you propably want call this function in onRequestPermissionsResult() for the case where the permission is not granted already. The onRequestPermissionsResult() function is located in your Activity class. It is called when the user granted or denied on of the permission requests the app made.
This could look as follows:
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// Ensure that this result is for the camera permission request
if (requestCode == PERMISSIONS_READ_CAMERA) {
// Check if the request was granted or denied
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// The request was granted -> tell the camera view
javaCameraView.setCameraPermissionGranted();
} else {
// The request was denied -> tell the user and exit the application
Toast.makeText(this, "Camera permission required.",
Toast.LENGTH_LONG).show();
this.finish();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
For more information about the permission system on Android have a look at the following resources:
Request App Permissions This site describes the process of requesting permissions with all necessary steps.
Permissions Overview This site has information about uses-feature in the manifest file. You probably want to add the following line to your manifest file: <uses-feature android:name="android.hardware.camera" android:required="true" /> to prevent the installation on devices without camera.
Now you'll see, that the onCameraFrame callback function is actually invoked. This will lead to a NullPointerException because mRGBAT is not initialized. To just see the camera image you can return inputFrame.rgba() directly in this function. This will at least show the camera image. All further steps are normal image processing to rotate / mirror the image.
I had the same problem in android 10. After a lot of trial and errors, I found that the following method must be implemented in the main activity:
#Override
protected List<? extends CameraBridgeViewBase> getCameraViewList() {
return Collections.singletonList(mOpenCvCameraView);
}
I'm using Android Beacon Library to scan for iBeacons. I'm using the HM-10 BLE module as a iBeacon. My problem is when i used the Android Beacon Library Sample codes, Nothing happens at all.
As mentioned in the sample code for starting an App in the Background, i created a new java class named "Backgroud" and the MainActivity class.
I want my application to start when a Beacon is detected when the app is not opened. Or show a notification (Toast) when the app is open.
I'm want also to know, what do we put in the MainActivity class.
Any help will be appreciated.
This is my AndroidManifest.xml file :
<application
android:allowBackup="true"
android:name=".Background"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
This is my MainActivity Java class :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
}
}
This is my Background Java class :
public class Background extends Application implements BootstrapNotifier {
private static final String TAG = ".Background";
private RegionBootstrap regionBootstrap;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "App started up");
BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
// wake up the app when any beacon is seen (you can specify specific id filers in the parameters below)
Region region = new Region("com.example.myapp.boostrapRegion", null, null, null);
regionBootstrap = new RegionBootstrap(this, region);
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region arg0) {
Log.d(TAG, "Got a didEnterRegion call");
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
//regionBootstrap.disable();
Intent intent = new Intent(this, MainActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
Toast.makeText(getApplicationContext(), "A Beacon is detected", Toast.LENGTH_LONG).show();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
}
I am using Vungle SDK 5.1.0.
In Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
[...]
<activity android:name="com.vungle.publisher.VideoFullScreenAdActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"/>
<activity android:name="com.vungle.publisher.MraidFullScreenAdActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen"/>
<activity android:name="com.vungle.publisher.FlexViewAdActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen"/>
In my first Activity:
final VunglePub vunglePub = VunglePub.getInstance();
[...]
vunglePub.init(this, "XXXXX", new String[] { "PLACEMEXXXXX" }, new VungleInitListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(Throwable e){
}
});
[...]
#Override
protected void onPause() {
super.onPause();
vunglePub.onPause();
}
#Override
protected void onResume() {
super.onResume();
vunglePub.onResume();
}
In my Main-Activity:
final VunglePub vunglePub = VunglePub.getInstance();
final AdConfig globalAdConfig = vunglePub.getGlobalAdConfig();
[...]
#Override
protected void onPause() {
super.onPause();
vunglePub.onPause();
}
#Override
protected void onResume() {
super.onResume();
vunglePub.onResume();
}
If I try to call
vunglePub.playAd("PLACEMEXXXXX", globalAdConfig);
I get noting. No Ads. And ideas how I can resolve my problem?
I am Gabor from Vungle. Is your app set to test mode in our dashboard? If yes, please switch to active mode and try again. Give it 30 minutes to be sure the app is really in active mode.
If you app is in active mode already, please contact us at tech-support#vungle.com with your Vungle APP ID and placement ID, so we can have a deeper look for you.
Thanks
Gabor
I am currently working on a music tuner that uses html5 and a webview to display the 'application'. I've written the all the permission required in manifest and I think for webview there's another permission required.
I am using this https://jbergknoff.github.io/guitar-tuner/ as a sample redirect page for now
Here's my manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.raynordev.projectrosin">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MICROPHONE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.audio.low_latency" />
<uses-feature android:name="android.hardware.audio.pro" />
<uses-feature android:name="android.hardware.microphone" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.raynordev.projectrosin.HomeActivity">
</activity>
</application>
</manifest>
Here's my .java
public class HomeActivity extends AppCompatActivity {
private WebView wv;
private String TAG = "HomeActivity";
private static final int REQUEST_INTERNET = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebView wv = (WebView) findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.setWebViewClient(new WebViewClient());
wv.setWebChromeClient(new WebChromeClient());
wv.loadUrl("https://jbergknoff.github.io/guitar-tuner/");
}
}
If require more information from me, please let me know.
Thank you everyone!!
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Example:
MainActivity
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 101;
private ActivityMainBinding mBinding;
private PermissionRequest myRequest;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setWebView();
}
private void setWebView() {
mBinding.webView.getSettings().setJavaScriptEnabled(true);
mBinding.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mBinding.webView.setWebViewClient(new WebViewClient());
mBinding.webView.getSettings().setSaveFormData(true);
mBinding.webView.getSettings().setSupportZoom(false);
mBinding.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mBinding.webViemBinding.webView.getSettings().setPluginState(WebSettings.PluginState.ON);
mBinding.webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onPermissionRequest(final PermissionRequest request) {
myRequest = request;
for (String permission : request.getResources()) {
switch (permission) {
case "android.webkit.resource.AUDIO_CAPTURE": {
askForPermission(request.getOrigin().toString(), Manifest.permission.RECORD_AUDIO, MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
break;
}
}
}
}
});
mBinding.webView.loadUrl("<your url");
}
#Override
public void onBackPressed() {
if (mBinding.webView.canGoBack()) {
mBinding.webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_RECORD_AUDIO: {
Log.d("WebView", "PERMISSION FOR AUDIO");
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
myRequest.grant(myRequest.getResources());
mBinding.webView.loadUrl("<your url>");
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void askForPermission(String origin, String permission, int requestCode) {
Log.d("WebView", "inside askForPermission for" + origin + "with" + permission);
if (ContextCompat.checkSelfPermission(getApplicationContext(),
permission)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
permission)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{permission},
requestCode);
}
} else {
myRequest.grant(myRequest.getResources());
}
}
}
Mainfest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MICROPHONE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.audio.low_latency" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-feature android:name="android.hardware.audio.pro" />
<uses-feature android:name="android.hardware.microphone"/>
Build.gradle:
android {
compileSdkVersion 26
defaultConfig {
applicationId "myapp.example.com.myapplication"
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
Summarising, you need the following components:
The MODIFY_AUDIO_SETTINGS permission.
A WebChromeClient and listen to callbacks for onPermissionRequest
Inside this callback, check for the the resources coming in the request object, create a global variable of this request object, iterate and look for specific permission inside the PermissionRequest class, ex. PermissionRequest.RESOURCE_VIDEO_CAPTURE which translates to the Manifest.permission.CAMERA permission, check if your app has this permission or not, using any mechanism you wish if not, request, if yes do 4.
In the permission callback or if the permission is granted, use the request object to grant the permission ex. request.grant(new String[]{PermissionRequest.RESOURCE_VIDEO_CAPTURE}) and you're good to go.
snippet:
webView.webChromeClient = object: WebChromeClient(){
override fun onPermissionRequest(request: PermissionRequest?) {
super.onPermissionRequest(request)
webkitPermissionRequest = request
request?.resources?.forEach {
when(it){
PermissionRequest.RESOURCE_AUDIO_CAPTURE-> {
askForWebkitPermission(it, Manifest.permission.RECORD_AUDIO, REQUEST_CODE_PERMISSION_AUDIO)
}
PermissionRequest.RESOURCE_VIDEO_CAPTURE->{
askForWebkitPermission(it, Manifest.permission.CAMERA, REQUEST_CODE_PERMISSION_CAMERA)
}
}
}
}
}
private fun askForWebkitPermission(webkitPermission: String, androidPermission: String, requestCode: Int){
val context = activity?: return
if (context.hasPermission(androidPermission)){
webkitPermissionRequest!!.grant(arrayOf(webkitPermission))
}else{
requestPermissions(arrayOf(androidPermission), requestCode)
}
}
Hope this helps.
Google's sample for the same: https://github.com/googlesamples/android-PermissionRequest
its problems for reload the webview , after too much research , found this code and create this below code :-
mwebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onPermissionRequest(final PermissionRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myRequest = request;
for (String permission : request.getResources()) {
if (permission.equals("android.webkit.resource.AUDIO_CAPTURE")) {
demandForPermission(request.getOrigin().toString(), Manifest.permission.RECORD_AUDIO, MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
} else {
myRequest.grant(request.getResources());
}
}
}
}
#Override
public void onPermissionRequestCanceled(PermissionRequest request) {
super.onPermissionRequestCanceled(request);
}
more info in this link Android Webview