I'm trying to implement an interstitial Ad activity insite my application whic is called every time that the user opens the settings.
The prblem is that even if the Ad unit ID is correct and the ad loading code is the same as google shows in their documentation the interstital ad doesn't load and always returns null.
I Also thought that maybe the app didn't have enough time to load the ad and then show it between the transaction from MainActivity to SettingsActivity, so i tried to start the IntersttitalAd with a PostDelayed runnable handler, but didn't work either.
Can anyone tell me why?
This is the InterstitialAdActivity:
public class InterstitialadActivity extends Activity {
private final String TAG = "Interstitialad debug";
private ProgressDialog progress;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progress = new ProgressDialog(this);
progress.setTitle("Loading Ad");
progress.setMessage("Wait while loading Interstitial Ad...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
Log.d(TAG, "The ad was dismissed.");
progress.dismiss();
finish();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
Log.d(TAG, "The ad failed to show.");
progress.dismiss();
finish();
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(TAG, "The ad was shown.");
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
String error =
String.format(
"domain: %s, code: %d, message: %s",
loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());
Log.d(TAG,"onAdFailedToLoad() with error: " + error);
mInterstitialAd = null;
}
});
// Show the ad if it's ready. Otherwise toast and restart the game.
if (mInterstitialAd != null) {
mInterstitialAd.show(this);
Log.d(TAG,"ad was shown");
} else {
Log.d(TAG,"ad was null");
progress.dismiss();
finish();
}
}
And this is how i call it the SettingsActivity:
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
...
if(!MainActivity.isPro) {
Intent myIntent = new Intent(SettingsActivity.this, InterstitialadActivity.class);
startActivity(myIntent);
}
}
Related
From the Flutter side, using the PlatformChannel, I am navigating to an Android Java activity, and doing some processes.
The activity successfully opens and I'm able to do the functionality and have the final result of it.
How may I navigate back to the Flutter side to a specific page and pass a value?
P.S.: without going back to the same page and then redirecting to the
next page.
On the Flutter side:
I have these variables
/// Filters Method Channel
final filtersChannel = const MethodChannel('flutter.native/filters');
/// Filters Method Channel
final filtersResultChannel = const MethodChannel("flutter.native/result_filters");
I have a floatingActionButton with this function which invokes a MethodChannel
Future<void> startNewActivity() async {
try {
await filtersChannel.invokeMethod('open_filters');
} on PlatformException catch (e) {
debugPrint("Failed to Invoke: '${e.message}'.");
}
}
On the MainActivity.java
On the protected void onCreate(#Nullable Bundle savedInstanceState) function, I'm starting an activity which has the AR video recording like this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, FiltersActivity.class);
startActivity(intent);
}
On the FiltersActivity.java
On the public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) function
I’m defining and invoking my two channels:
The flutter.native/result_filters channel which builds the UI and
the functionality.
The flutter.native/filters channel which returns the final result.
Here:
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
String resultFiltersChannelIdentifier = "flutter.native/result_filters";
filtersResultChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), resultFiltersChannelIdentifier);
String filtersChannelIdentifier = "flutter.native/filters";
MethodChannel filtersChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), filtersChannelIdentifier);
filtersChannel.setMethodCallHandler(this::filtersMethodCallHandler);
}
Then, the flutter.native/filters displays the UI using the filtersMethodCallHandler function. Here:
private void filtersMethodCallHandler(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("open_filters")) {
openUI();
} else {
result.notImplemented();
}
}
In the openUI function, I'm assigning the record button a function, here:
recordButton.setOnClickListener(this::toggleRecording);
And here's the toggleRecording function:
public void toggleRecording(View unusedView) {
boolean recording = videoRecorder.onToggleRecord();
if (recording) {
recordButton.setImageResource(R.drawable.round_stop);
Toast.makeText(this, "Started Recording", Toast.LENGTH_SHORT).show();
} else {
recordButton.setImageResource(R.drawable.round_videocam);
Toast.makeText(this, "Recording Stopped", Toast.LENGTH_SHORT).show();
videoPath = videoRecorder.getVideoPath().getAbsolutePath();
Toast.makeText(this, "Video saved: " + videoPath, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Video saved: " + videoPath);
// Send notification of updated content.
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.TITLE, "Sceneform Video");
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.Video.Media.DATA, videoPath);
getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
filtersResultChannel.invokeMethod("filters_result", videoPath);
finish();
}
}
As shown above, I'm invoking the filters_result method for the filtersResultChannel channel and I'm adding the videoPath to it.
And then, I'm calling the finish(); method to close the FiltersActivity and return back to the MainAvtivity which successfully returns me to the Flutter page!
BACK to the Flutter side,
I'm listening to the filtersResultChannel like this:
#override
void initState() {
super.initState();
filtersResultChannel.setMethodCallHandler(_filtersResultHandler);
}
Future _filtersResultHandler(MethodCall methodCall) async {
if (methodCall.method == "filters_result") {
final videoPath = methodCall.arguments;
if (videoPath != null && videoPath.length >= 0) {
SchedulerBinding.instance.addPostFrameCallback((_) {
debugPrint("YES YES YES => $videoPath");
setState(() {
reportStatus = videoPath;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoShow(clipPath: videoPath),
),
);
});
});
}
return null;
} else {
return null;
}
}
As shown above, I have a debugPrint statement, this statement prints the returned videoPath from the filtersResultChannel
<--------->
THE PROBLEM
<--------->
Even though I'm successfully getting the videoPath value and successfully returning back to the Flutter page, I'm NOT able to use it!!
The setState(); doesn't update the UI NOR navigate to the next screen, the VideoShow screen!
HOW MAY I FIX SUCH AN ISSUE?
I have made an android app using Android Studio and I have implemented Google AdMob into it.
However, when it comes to showing ads, whenever I try to show it from a function, it does not show.
Here is the function:
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.jodastudios.universalskyremote", Context.MODE_PRIVATE);
int clicks = sharedPreferences.getInt("clicks", 0);
sharedPreferences.edit().putInt("clicks", 0);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
Whenever I show the ads on the OnCreate method, they show.
Here is the code:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.jodastudios.universalskyremote", Context.MODE_PRIVATE);
int clicks = sharedPreferences.getInt("clicks", 0);
sharedPreferences.edit().putInt("clicks", 0);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
},9000);
I don't know why the ads are not showing from a function: does anybody know how to fix this?
Second code is delayed for 9 sec and that's enough time for the ad to load.
Function cannot display ad that has not been loaded!
You have to set AdListener and show add from onAdLoaded method or create callback to show from activity...
...or call your function from onAdLoaded(){
InterstitialAd interstitialAd = new InterstitialAd(context);
interstitialAd.setAdUnitId(adIdent);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
interstitialAd.show();
//TODO or create callback to show from activity
if (adCallback != null) {
adCallback.onAdLoaded();
}
}
.....................
.....................
}
and
interstitialAd.loadAd(new AdRequest.Builder().build());
I have built a small chat app using firebase. I have also implemented firebaseui for logging in. The problem I am facing is, if the user has not signed up. Whenever the app launches it should take me directly to FirebaseUi signup options but what is happening with current code is for a milli second it shows the layout of main activity and then goes to FirebaseUi.
Also when I am pressing back button before exiting it again shows me the layout of main activity. I want the activity to get destroyed and take me to home (android) but it shows me main activity for a millisecond and then the app exits.
Why is this happening?
public class MainActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 1;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private TextView mUserNameTextView;
private Button mSignOutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUserNameTextView = (TextView) findViewById(R.id.user_name_text_view);
mSignOutButton = (Button) findViewById(R.id.sign_out_button);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
mUserNameTextView.setText(user.getDisplayName());
} else {
// User is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()))
.build(),
RC_SIGN_IN);
}
}
};
mSignOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
}
private void signOut() {
FirebaseAuth.getInstance().signOut();
mUserNameTextView.setText("");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
// when app is paused remove the state listener
mAuth.removeAuthStateListener(mAuthStateListener);
}
}
#Override
protected void onResume() {
super.onResume();
// adding the state listener
mAuth.addAuthStateListener(mAuthStateListener);
}
}
I believe you won't be able to make the Main Activity not display for a millisecond upon app start, since you are first opening the Main Activity and then you redirect it (if I understood correctly).
I can however help you with your problem when you press the back button.
Add this to your FirebaseUi code as a normal method:
#Override
public void onBackPressed() {
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
//replace "CurrentActivity" and "NextActivity" with your activity names
startActivity(intent);
}
This will open the activity you want when the back button is pressed.
When you start new activity after logged in using FirebaseUI then you need to finish(will remove the activity from backstack) the Login Activity when you start activity.
Intent intent = new Intent(ActivityA.this, NextActivity.class);
startActivity(intent);
finish();
I'm trying to show ad When user presses on sound card 10 times but when I press on sound card 10th time no ad is shown and no sound plays anymore until I press stop button after which sound plays again until I press it 10 times again
Part of my main activity:
..
MobileAds.initialize(this,
"ca-app-pub-2470537820941001~1050614569");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mPowerSaverChangeReceiver);
if (mSoundPlayer != null) {
mSoundPlayer.release();
mSoundPlayer = null;
}
}
#Override
public void onResume() {
super.onResume();
if (mSoundPlayer == null) mSoundPlayer = new SoundPlayer(MainActivity.this);
}
#Override
public void onPause() {
super.onPause();
if (mSoundPlayer != null) {
mSoundPlayer.release();
mSoundPlayer = null;
}
}
this is my sound player class:
class SoundPlayer {
private MediaPlayer mPlayer;
private Context mContext;
private static final String TAG = "SoundPlayer";
private int counter = 0;
private void playSound(Sound sound) {
int resource = sound.getResourceId();
if (counter == 5) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
} else {
counter++;
}
if (mPlayer != null) {
if (mPlayer.isPlaying())
mPlayer.stop();
mPlayer.reset();
../
The error
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.ads.InterstitialAd.isLoaded()' on a null object reference
at my.app.SoundPlayer.playSound(SoundPlayer.java:38)
at my.app.reactionsounds.SoundPlayer.onEvent(SoundPlayer.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:507)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:501)
at org.greenrobot.eventbus.AsyncPoster.run(AsyncPoster.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
You have not initialised interstiial Ad in your sound player class.Your error shows clearly that Interstitial ad is null.
interstitialAd = new InterstitialAd(ReadingPage.this);
interstitialAd.setAdUnitId(getResources().getString(R.string.interstitial1));
interstitialAd.loadAd(new AdRequest.Builder().build());
When I upgraded from the old Google AdMob SDK to the new Google Pay Services SDK, I noticed a difference in how quickly the interstitial ad closes and starts the next activity (which also brings up a new layout). In the past, it was near instant. Now, with the new Play Services interstitial, I have noticed a 1-2 second delay after clicking "x" on the interstitial before the new activity starts.
How can I get rid of this delay?
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(AD_UNIT_ID);
AdRequest adRequest = new AdRequest.Builder().build();
final Intent nextActive = new Intent("activity");
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
//Intent nextActive = new Intent("activity");
startActivity(nextActive);
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
//Intent nextActive = new Intent("activity");
startActivity(nextActive);
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
#Override
public void onAdLoaded() {
displayInterstitial();
super.onAdLoaded();
}
});