I am trying to use the AdMob Rewarded Ad in my Android application.
In order to include it in the refered app, I need to wait for the rewarded video to load after the user click the buttom.
I am trying it throughout the code bellow, but I get the error:
java.lang.IllegalStateException: showAd must be called on the main UI
thread.
When the buttom is clicked:
b_r_ans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSomBotaoLigado() && loaded[0])
soundPool.play(soundID, MyApplication.getVolumeBotao(), MyApplication.getVolumeBotao(), 1, 0, 1f);
Toast.makeText(MyApplication.getAppContext(),carregando_rv, Toast.LENGTH_LONG).show();
Thread t_rv = new Thread(new Runnable() {
public void run() {
while(!rv_loaded){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t_rv.start();
try {
t_rv.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
mRewardedVideoAd.show();
}
});
Overrided the listener:
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
rv_loaded = true;
}
Using the mRewardedVideoAd.isLoaded() function triggers the same issue.
How can I wait for the video to load properly?
It appears to happen that you are calling show from a different thread to the UI so I'd try to force its execution on the main thread like:
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
};
mainHandler.post(myRunnable);
You can also disable the button until the ad is loaded, then in the onRewardedVideoAdLoaded function enable the button:
override fun onRewardedVideoAdLoaded() {
ad_btn.isEnabled = true
}
Hope it helps. This is the implementation that I am using.
Solved it through this code:
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
rv_loaded = true;
if(goToAnswers)
mRewardedVideoAd.show();
goToAnswers = false;
}
b_r_ans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSomBotaoLigado() && loaded[0])
soundPool.play(soundID, MyApplication.getVolumeBotao(), MyApplication.getVolumeBotao(), 1, 0, 1f);
Toast.makeText(MyApplication.getAppContext(),carregando_rv, Toast.LENGTH_LONG).show();
if(mRewardedVideoAd.isLoaded())
mRewardedVideoAd.show();
else goToAnswers=true;
}
});
This code will show a ProgressDialog while loading the reward video:
package com.mountzoft.waitForrewardvideoProperly;
import android.app.ProgressDialog;
import android.content.Context;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class MainActivity extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mAd;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Please wait... Loading Reward Video Ad!");
mProgressDialog.setCancelable(false);
}
private final showRewardVideoAd() {
mProgressDialog.show();
initializeRewardVideoAd();
loadRewardedVideoAd();
}
private void initializeRewardVideoAd(){
String adMobAppId = BuildConfig.AD_MOB_APP_ID; //id is stored in build gradle file
MobileAds.initialize(this, adMobAppId);
mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(this);
}
private void loadRewardedVideoAd() {
String admobAdUnitId = BuildConfig.ADMOB_AD_UNIT_ID;//id is stored in build gradle
mAd.loadAd(admobAdUnitId,
new AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
mAd.show();
}
#Override
public void onRewardedVideoAdOpened() {
mAd = null;
}
#Override
public void onRewardedVideoStarted() {
mProgressDialog.dismiss();
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted(){
}
}
If you need to wait until rewarded ad loading use SingleLiveEvent. Please refer following code snippet.
private val isRewardedAdLoaded: LiveData<Event<Boolean>>
get() = _isRewardedAdLoaded
private var _isRewardedAdLoaded: MutableLiveData<Event<Boolean>> = MutableLiveData()
I used this is in fragment. So this from onViewCreated()
rewardedAd = createAndLoadRewardedAd()
and I post loading state as following
private fun createAndLoadRewardedAd(): RewardedAd {
val rewarded = RewardedAd(requireContext(), getString(R.string.admob_rewarded_id_test))
val adLoadCallback = object : RewardedAdLoadCallback() {
override fun onRewardedAdLoaded() {
Log.e(TAG, "onRewardedAdLoaded")
_isRewardedAdLoaded.postValue(Event(true))
}
override fun onRewardedAdFailedToLoad(errorCode: Int) {
_isRewardedAdLoaded.postValue(Event(false))
}
}
rewarded.loadAd(Builder().build(), adLoadCallback)
return rewarded
}
this is rewarded ad show method
private fun showRewardedAds(rewarded: RewardedAd) {
rewarded.show(requireActivity(), object : RewardedAdCallback() {
override fun onRewardedAdOpened() {
Log.e(TAG, "onRewardedAdOpened")
}
override fun onRewardedAdClosed() {
Log.e(TAG, "onRewardedAdClosed")
rewardedAd = createAndLoadRewardedAd()
}
override fun onUserEarnedReward(rewardItem: RewardItem) {
Log.e(TAG, "onUserEarnedReward")
translateText()
}
override fun onRewardedAdFailedToShow(errorCode: Int) {
translateText()
}
})
}
Finally I called as following
R.id.btnTranslate -> {
if (rewardedAd.isLoaded){
showMessage(
getString(R.string.translate_ads_show_warning_title),
getString(R.string.translate_ads_show_warning_msg)
)
} else {
progress.setVisible(true)
isRewardedAdLoaded.observe(viewLifecycleOwner, Observer {
it.getContentIfNotHandled()?.let { loaded ->
if (loaded and progress.isVisible){
progress.setVisible(false)
showMessage(
getString(R.string.translate_ads_show_warning_title),
getString(R.string.translate_ads_show_warning_msg)
)
}
}
})
}
}
Related
I'm trying to integrate the interstitial ad from Huawei Ads, when I click on (X) or back button to close the ad, for some reason the Toast inside onAdClosed method is not showing.
huaweiInterstitialAd = new InterstitialAd(MainActivity.this);
huaweiInterstitialAd.setAdId("teste9ih9j0rc3");
private void showHuaweiInterstitial() {
if (huaweiInterstitialAd != null && huaweiInterstitialAd.isLoaded()) {
huaweiInterstitialAd.show(MainActivity.this);
}
}
public void loadHuaweiInterstitialAd() {
huaweiInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
showHuaweiInterstitial();
}
#Override
public void onAdFailed(int errorCode) {
Log.d(TAG, "Ad load failed with error code: " + errorCode);
}
#Override
public void onAdLeave() {
super.onAdLeave();
Log.d(TAG, "onAdLeave");
}
#Override
public void onAdClosed() {
super.onAdClosed();
Toast.makeText(MainActivity.this, "Ad Closed", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdClicked() {
Log.d(TAG, "onAdClicked");
super.onAdClicked();
}
#Override
public void onAdOpened() {
Log.d(TAG, "onAdOpened");
super.onAdOpened();
}
});
AdParam adParam = new AdParam.Builder().build();
huaweiInterstitialAd.loadAd(adParam);
}
The problem only occurs if you use:
implementation 'com.huawei.hms:ads:3.4.46.300'
But everything works fine with :
implementation 'com.huawei.hms:ads-lite:13.4.46.300'
I'm actually trying to use the useroffroute function but it's not working, I saw this other post and it said to NavigationView, only I don't know how to do it exactly. I am currently using this code to detect if the user has left the route, but he is not calling the useroffroute function. What I'm trying to do is that when the user leaves the route he fires a Toast for the user, but unfortunately I was not successful.
public class mapbox extends AppCompatActivity{
private MapView mapView;
Button button;
private static final String TAG = "resultados";
private MapboxNavigation navigation;
private boolean running;
private NavigationMapboxMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_mapbox);
button = findViewById(R.id.button);
MapboxNavigationOptions options = MapboxNavigationOptions.builder().isDebugLoggingEnabled(true).build();
navigation = new MapboxNavigation(getApplicationContext(), getString(R.string.mapbox_access_token), options);
/*
navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
// Make sure you call for a new DirectionsRoute object
// and end by calling MapboxNavigation#startNavigation on a successful
}
});
*/
/*
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}
});
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// From Mapbox to The White House
Point origin = Point.fromLngLat(-38.62882018, -3.78666528);
Point destination = Point.fromLngLat(-38.56038094, -3.7337361F);
NavigationRoute.builder(mapbox.this)
.accessToken(getString(R.string.mapbox_access_token))
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.i(TAG, response+"");
// Route fetched from NavigationRoute
DirectionsRoute route = response.body().routes().get(0);
// Create a NavigationLauncherOptions object to package everything together
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(false)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(mapbox.this, options);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
//mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
//mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
//mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
//mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
//mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
//mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
//mapView.onDestroy();
}
}
After many hours looking for a solution, I finally found one. You have to use NavigationViewer to obtain the parameters that the application passes, so you can listen if the user leaves the route. Here's an example:
public class last extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, RouteListener, ProgressChangeListener {
private NavigationView navigationView;
private boolean dropoffDialogShown;
private Location lastKnownLocation;
private List<Point> points = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
points.add(Point.fromLngLat(-38.62882018, -3.78666528));
points.add(Point.fromLngLat(-38.56038094, -3.7337361));
setContentView(R.layout.activity_last);
navigationView = findViewById(R.id.navigationView);
navigationView.onCreate(savedInstanceState);
navigationView.initialize(this);
}
#Override
public void onStart() {
super.onStart();
navigationView.onStart();
}
#Override
public void onResume() {
super.onResume();
navigationView.onResume();
}
#Override
public void onLowMemory() {
super.onLowMemory();
navigationView.onLowMemory();
}
#Override
public void onBackPressed() {
// If the navigation view didn't need to do anything, call super
if (!navigationView.onBackPressed()) {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
navigationView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
navigationView.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
navigationView.onPause();
}
#Override
public void onStop() {
super.onStop();
navigationView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
}
#Override
public void onNavigationReady(boolean isRunning) {
fetchRoute(points.remove(0), points.remove(0));
}
#Override
public void onCancelNavigation() {
// Navigation canceled, finish the activity
finish();
}
#Override
public void onNavigationFinished() {
// Intentionally empty
}
#Override
public void onNavigationRunning() {
// Intentionally empty
}
#Override
public boolean allowRerouteFrom(Point offRoutePoint) {
return true;
}
#Override
public void onOffRoute(Point offRoutePoint) {
Toast.makeText(this, "Off route", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteAlong(DirectionsRoute directionsRoute) {
}
#Override
public void onFailedReroute(String errorMessage) {
}
#Override
public void onArrival() {
if (!dropoffDialogShown && !points.isEmpty()) {
showDropoffDialog();
dropoffDialogShown = true; // Accounts for multiple arrival events
Toast.makeText(this, "You have arrived!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
lastKnownLocation = location;
}
private void startNavigation(DirectionsRoute directionsRoute) {
NavigationViewOptions navigationViewOptions = setupOptions(directionsRoute);
navigationView.startNavigation(navigationViewOptions);
}
private void showDropoffDialog() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage(getString(R.string.dropoff_dialog_text));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dropoff_dialog_positive_text),
(dialogInterface, in) -> fetchRoute(getLastKnownLocation(), points.remove(0)));
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dropoff_dialog_negative_text),
(dialogInterface, in) -> {
// Do nothing
});
alertDialog.show();
}
private void fetchRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.alternatives(true)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
DirectionsResponse directionsResponse = response.body();
if (directionsResponse != null && !directionsResponse.routes().isEmpty()) {
startNavigation(directionsResponse.routes().get(0));
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
private NavigationViewOptions setupOptions(DirectionsRoute directionsRoute) {
dropoffDialogShown = false;
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.directionsRoute(directionsRoute)
.navigationListener(this)
.progressChangeListener(this)
.routeListener(this)
.shouldSimulateRoute(false);
return options.build();
}
private Point getLastKnownLocation() {
return Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.services.android.navigation.ui.v5.NavigationView
android:id="#+id/navigationView"
android:layout_width="0dp"
android:layout_height="0dp"
app:navigationLightTheme="#style/NavigationViewLight"
app:navigationDarkTheme="#style/NavigationViewDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
When I start navigation with multiple waypoints, the navigation stops after reaching first waypoint.
Please suggest changes.`
try{
NavigationRoute.Builder builder = NavigationRoute.builder(this)
.accessToken("pk." + getString(R.string.gh_key))
.baseUrl(getString(R.string.base_url))
.user("gh")
.alternatives(true);
Location lastKnownLocation = new Location(LocationManager.GPS_PROVIDER);
lastKnownLocation.setLatitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.latitude))));
lastKnownLocation.setLongitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.longitude))));
Point location = Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
if (lastKnownLocation.hasBearing()){
// 90 seems to be the default tolerance of the SDK
builder.origin(location, (double) lastKnownLocation.getBearing(), 90.0);
}
else{
builder.origin(location);
}
try {
if(waypoints.size()>0){
for (int i = 0; i < waypoints.size(); i++) {
Point p = waypoints.get(i);
if (i < waypoints.size() - 1) {
try {
builder.addWaypoint(p);
}catch (Exception e){
e.printStackTrace();
}
} else {
builder.destination(p);
}
}
}
}catch (Exception se){
se.printStackTrace();
}
builder.build().getRoute(new SimplifiedCallback() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (validRouteResponse(response)) {
route = response.body().routes().get(0);
try {
MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(MapBoxNavActivity.this);
options.directionsRoute(route);
options.shouldSimulateRoute(false);
options.directionsProfile(DirectionsCriteria.PROFILE_DRIVING_TRAFFIC);
navigationOptions.enableOffRouteDetection(true);
navigationOptions.snapToRoute(true);
options.navigationOptions(navigationOptions.build());
navigationView.startNavigation(options.build());
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
super.onFailure(call, throwable);
Log.i("Fetch route error",throwable.getMessage());
}
});
}
}
catch ( Exception se){
se.printStackTrace();
}
}
`
i have a recycler view and i want to control of downloading using buttons in my card view.
i use PRDownloader library but i have issue i can't resume download after finish the app and open it again it start the download not resume it.
my code as below
holder.downloadResumeOrPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downLoadID = PRDownloader.download(remoteLink, myLocalDirectory,
fileName)
.build()
.setOnStartOrResumeListener(new OnStartOrResumeListener() {
#Override
public void onStartOrResume() {
holder.pauseDownloadBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.downloadResumeOrPlayBtn.setVisibility(View.GONE);
notifyDataSetChanged();
}
})
.setOnPauseListener(new OnPauseListener() {
#Override
public void onPause() {
holder.pauseDownloadBtn.setText(mContext.getResources().getString(string.resume_text_btn));
holder.downloadResumeOrPlayBtn.setVisibility(View.GONE);
holder.pauseDownloadBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.GONE);
notifyDataSetChanged();
}
})
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel() {
holder.mProgressBar.setProgress(0);
holder.downloadResumeOrPlayBtn.setText(mContext.getResources().getString(R.string.download_text));
holder.downloadResumeOrPlayBtn.setVisibility(View.VISIBLE);
holder.pauseDownloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
notifyDataSetChanged();
}
})
.setOnProgressListener(new OnProgressListener() {
#Override
public void onProgress(Progress progress) {
video.setVideoProgress(progress.currentBytes * 100 / progress.totalBytes);
Log.i("videosAdapter", video.getVideoProgress() + "");
holder.mProgressBar.setProgress((int) video.getVideoProgress());
holder.mProgressBar.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
})
.start(new OnDownloadListener() {
#Override
public void onDownloadComplete() {
System.out.println("download completed");
holder.downloadResumeOrPlayBtn.setText(mContext.getResources().getString(string.play_video_text));
holder.downloadResumeOrPlayBtn.setVisibility(View.VISIBLE);
holder.pauseDownloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
notifyDataSetChanged();
}
#Override
public void onError(Error error) {
holder.downloadResumeOrPlayBtn.setText(mContext.getResources().getString(string.download_text));
Toast.makeText(mContext, error.getServerErrorMessage(), Toast.LENGTH_SHORT).show();
holder.mProgressBar.setProgress(0);
}
});
}
if(holder.downloadResumeOrPlayBtn.getText().toString().equals(mContext.getResources().getString(string.resume_text_btn)))
{
PRDownloader.resume(downLoadID);
}
});
my question is how to resume the download without downloading the file from the start and if there is another library to use how can i make it.
I want to use Rewarded video ads (Admob) but I want to show a progress bar while the video ads is loading
I already try to did it with async task just to see if the video will load but it didn't work
#SuppressLint("StaticFieldLeak")
public class videoAd extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(Void... voids) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
});
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (mRewardedVideoAd.isLoaded()){
Toast.makeText(SetFullWallpaper.this, "Video loaded", Toast.LENGTH_SHORT).show();
mRewardedVideoAd.show();
}
}
}
Now I want to load a progress bar if the video is not loaded yet
Thank you
This is how I did it:
I had a button, which when clicked showed the ad, so I had a boolean variable which tracked whether the button has been clicked:
boolean buttonClicked = false
These lines were in my onCreate function:
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getContext());
rewardedVideoAdListener = new RewardedVideoAdListener() {
#Override
public void onRewardedVideoAdLoaded() {
if(buttonClicked) {
showAd();
}
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
if(buttonClicked) {
progressBar.setVisibility(View.INVISIBLE);
Toast toast = Toast.makeText(getContext(), "Please try again later", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRewardedVideoCompleted() {
}
};
mRewardedVideoAd.setRewardedVideoAdListener(rewardedVideoAdListener);
loadRewardedVideoAd();
pointsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAd();
}
});
This was my showAd function:
public void showAd(){
if (mRewardedVideoAd.isLoaded()) {
progressBar.setVisibility(View.GONE);
mRewardedVideoAd.show();
buttonClicked = false;
} else {
loadRewardedVideoAd();
progressBar.setVisibility(View.VISIBLE);
buttonClicked = true;
}
}
How this works is, the app tries to load the ad in the background by calling the loadRewaredVideoAd() function when the activity/fragment is created. Then when the user clicks the button,showAd() function is called and one of two things happen:
1) If the ad was successfully loaded, it shows the ad.
2) If not, it calls loadRewardedVideoAd() again and shows a progressbar this time. It also sets buttonClicked to true. Then if the ad loads, the onRewardedVideoAdLoaded() function is called which calls showAd() again and this time the 1st option happens.
If the ad didn't load this time as well, then onRewardedVideoAdFailedToLoad(int i)is called and it shows a toast saying the user to try again later.
add OnProgressUpdate() in your class that extends AsyncTask and add progress dialog in this.
I am placing an admob video, which is executed when you enter the activity. In my case, I put an executable loop to start the video when it is already loaded.
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
This is part of all my code
private boolean started = false;
private Handler handler = new Handler();
private void initializeAdMob() {
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(getString(R.string.id_block_activity), new AdRequest.Builder().build());
}
}
private void showRewardedVideoAd() {
if (BaseInteractor.isNetworkAvailable(this)) {
showProgressBar(true);
start();
}
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
if (started) {
start();
}
}
};
public void stop() {
started = false;
handler.removeCallbacks(runnable);
}
public void start() {
started = true;
handler.postDelayed(runnable, 2000);
}
finally I stop the runnable in
#Override
public void onRewardedVideoAdOpened() {
showProgressBar(false);
stop();
}
I hope this helps you.
I was having some problem for Android activity transition. Basically what I am trying to do is share text to Twitter. However, when I open up the twitter content, it took quite a few seconds to load up the content and resulting in the white blank activity for a few seconds.
And here is my codes, when my button onClick, I am executing the loading dialog:
ivTwitterShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Thread newThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000);
} catch (Exception e) {
} finally {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(tweetUrl));
startActivity(intent);
progressDialog.dismiss();
}
}
};
newThread.start();
new LoadTwitterTask().execute();
}
});
private class LoadTwitterTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "Loading Twitter...",
"Retrieving Twitter information, please wait...", false,
false);
EventDialogueBox.customizeDialogueBox(context, progressDialog);
}
#Override
protected Void doInBackground(Void... params) {
try {
synchronized (this) {
int counter = 0;
while (counter <= 4) {
this.wait(50);
counter++;
publishProgress(counter * 25);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
}
}
However, my problem now is the white blank page before the content is loaded up still there. What I wanted is firstly, the loading dialog will show. Then, at the same time, the twitter intent is loading. Once finish loaded up the content, then dialog will be dismissed.
Any ideas?
Thanks in advance.