I have created a function to show interstitial ad before showing another activity.
It's working but onAdDismissedFullScreenContent is being called 2-3 sec lately after closing the ad. It causes previous screen to stand-by.
There's a chance to re-click the button to show the wanted Activity.
I really don't understand how to resolve this issue.
Here is my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AdManager.showInterstitial(MainActivity.this, () -> {
Intent i = new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
});
}
});
AdManager.loadInterstitial(this);
}
}
And this is Application Class:
public class App extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
AdManager.Init(this);
}
public static Context getContext() {
return mContext;
}
}
AdManager Class:
public class AdManager {
private static InterstitialAd mInterstitialAd;
private static boolean loading, showing;
public static void Init(Context context) {
MobileAds.initialize(context, initializationStatus -> {
loadInterstitial(context);
});
}
public static void loadInterstitial(Context context) {
if (context == null)
context = App.getContext();
Context finalContext = context;
if (mInterstitialAd != null) {
Toast.makeText(context,"already loaded",Toast.LENGTH_LONG).show();
return;
}
if (loading) {
Toast.makeText(context,"already another request is processing",Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(context,"requesting interstitial",Toast.LENGTH_LONG).show();
loading = true;
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(context, "Interstial Ad Unit ID", adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
Toast.makeText(finalContext,"ad loaded",Toast.LENGTH_LONG).show();
loading = false;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
loading = false;
Toast.makeText(finalContext,"ad failed to load",Toast.LENGTH_LONG).show();
}
});
}
public static void showInterstitial(Activity activity, #NonNull AdListener listener) {
if (showing) {
Toast.makeText(activity,"already showing",Toast.LENGTH_LONG).show();
listener.onCompleted();
return;
}
if (mInterstitialAd != null) {
showNow(activity, listener);
} else {
Toast.makeText(activity,"mInterstitialAd is null",Toast.LENGTH_LONG).show();
listener.onCompleted();
loadInterstitial(activity.getApplicationContext());
}
}
private static void showNow(Activity activity, AdListener listener) {
if (mInterstitialAd != null && !showing) {
showing = true;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
Toast.makeText(activity,"Ad dismissed",Toast.LENGTH_LONG).show();
mInterstitialAd = null;
listener.onCompleted();
showing = false;
// times to load an new interstitial ad content
loadInterstitial(activity.getApplicationContext());
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
Toast.makeText(activity,"AdFailedToShowFullScreenContent",Toast.LENGTH_LONG).show();
mInterstitialAd = null;
listener.onCompleted();
showing = false;
// times to load an new interstitial ad content
loadInterstitial(activity.getApplicationContext());
}
});
// Now show the ad
Toast.makeText(activity,"call to show ad",Toast.LENGTH_LONG).show();
mInterstitialAd.show(activity);
} else {
Toast.makeText(activity,"either mInterstitialAd is null or ad already is showing",Toast.LENGTH_LONG).show();
listener.onCompleted();
}
}
public interface AdListener {
void onCompleted();
}
}
Please help.
The delay problem
You can't really help it. The problem is from the admob. This will happen. But, to know more about it, we can post an issue abt that on the Google Issue Tracker.
The button problem
I dont think this is any hard task. Just follow the steps:
Create a ProgressBar in your xml layout on top of the button and set its visibility to gone
When the button is click and the ad is shown, you can set the button to invisible and the progress bar can be set to invisible.
Then after a delay, the other activity opens without any harm to the activity from NullPointerException
Related
These days I am doing a test, the objective is to click on a button to go to activity2 and show the interstitial advertising. For now this is the result thanks to information from: link
The problem:
Upon returning to the main page (MainActivity), I pressed the button to re-enter activity2 and it is no longer displayed. Only if I close the application and open the application and press the activity button 2 the advertising is displayed.
MainActivity code
public class MainActivity extends Activity {
private InterstitialAd mInterstitialAd;
private static final String TAG = "InfoApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//***** Initialize the Mobile Ads SDK.*********** -//
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//**********************************************************//
adrequest_interstitial = new AdRequest.Builder().build();
InterstitialAd.load(this,ConfigPubli.Ads_interstitial, adrequest_interstitial,
new InterstitialAdLoadCallback()
{
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd)
{
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError)
{
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
public void adstot(Intent i){
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
startActivity(i);
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
mInterstitialAd = null;
startActivity(i);
}
});
}
public void page2(View view){ //button
Intent i = new Intent (this, Activity2.class);
i.putExtra("valor","page2");
int randomAd = (int)(Math.random()*10);
if (mInterstitialAd != null && randomAd<=1) {
adstot(i);
mInterstitialAd.show(this);
}
else{
startActivity(i);
}
}
}
Thanks for the answers
Whenever InterstitialAd has been shown, the variable mInterstitialAd was set to null. So, how mInterstitialAd can be shown twice?
You should make a new request to get an interstitial just after mInterstitialAd = null;
Try like below:
public class MainActivity extends Activity {
private InterstitialAd mInterstitialAd;
private static final String TAG = "InfoApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//***** Initialize the Mobile Ads SDK.*********** -//
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
// Initialization complete
// You are now free to make an ad request
loadAnInterstitial();
}
});
//**********************************************************//
}
private void loadAnInterstitial(){
adrequest_interstitial = new AdRequest.Builder().build();
InterstitialAd.load(this,ConfigPubli.Ads_interstitial, adrequest_interstitial,
new InterstitialAdLoadCallback()
{
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd)
{
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError)
{
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
public void adstot(Intent i){
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
mInterstitialAd = null;
startActivity(i);
// make a new ad request here
loadAnInterstitial();
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
mInterstitialAd = null;
startActivity(i);
// make a new ad request here
loadAnInterstitial();
}
});
}
public void page2(View view){ //button
Intent i = new Intent (this, Activity2.class);
i.putExtra("valor","page2");
int randomAd = (int)(Math.random()*10);
if (mInterstitialAd != null && randomAd<=1) {
adstot(i);
mInterstitialAd.show(this);
}
else{
startActivity(i);
// make a new ad request here
loadAnInterstitial();
}
}
}
That's all. Hope it will help.
Updated code (another version):
I have added an (if), after 6 clicks of the button it will load a new ad.
public void page2(View view){ //button
Intent i = new Intent (this, Activity2.class);
i.putExtra("valor","page2");
int randomAd = (int)(Math.random()*10);
if (mInterstitialAd != null && randomAd<=1) {
adstot(i);
mInterstitialAd.show(this);
}
else{
startActivity(i);
if(countclick==6)
{
loadAnInterstitial();
}else{
countclick=countclick+1;
}
}
}
It works!, I hope that google admob does not consider that it is poorly implemented.
So, i want to make an app with a simple button that shows an rewarded ad. The button works and shows a rewarded ad but when i press again no rewarded ad is showing.
I want to show ad for every button click.
this is the code:
public class MainActivity extends AppCompatActivity {
private RewardedAd rewardedAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
TextView textView = (TextView) findViewById(R.id.textView);
rewardedAd = new RewardedAd(this,
"ca-app-pub-3940256099942544/5224354917");
final RewardedAdLoadCallback[] adLoadCallback = {new RewardedAdLoadCallback() {
#Override
public void onRewardedAdLoaded() {
// Ad successfully loaded.
}
#Override
public void onRewardedAdFailedToLoad(LoadAdError adError) {
// Ad failed to load.
}
}};
rewardedAd.loadAd(new AdRequest.Builder().build(), adLoadCallback[0]);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (rewardedAd.isLoaded()) {
Activity activityContext = MainActivity.this;
RewardedAdCallback adCallback = new RewardedAdCallback() {
#Override
public void onRewardedAdOpened() {
// Ad opened.
}
#Override
public void onRewardedAdClosed() {
}
#Override
public void onUserEarnedReward(#NonNull RewardItem reward) {
}
#Override
public void onRewardedAdFailedToShow(AdError adError) {
// Ad failed to display.
}
};
rewardedAd.show(activityContext, adCallback);
} else {
Log.d("TAG", "The rewarded ad wasn't loaded yet.");
}
}
});
}
}
I didnt set the reward , first i want the button to be able to show multiple ads
You should reload ads, like this :
https://developers.google.com/admob/android/rewarded-ads
I am trying to create a class which can be called from any activity to speak the text from an EditText box. When I run the code I currently have, it plays the alert sound but then fails to play the Text to Speech content. What do I need to change to get the text to play too? I know the activity layout XML code is correct because the Text To Speech code works when it is directly in the activity class. I have looked around for a solution but nowhere else outlines how to do this from a thread context.
I have included my code below:
on AircraftMain.java
View.OnClickListener speakBtnOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String toSpeak = textToSpeak.getText().toString();
TextToSpeak speak = new TextToSpeak(AircraftMain.this, toSpeak);
speak.run();
}
};
TextToSpeak.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import java.util.Locale;
public class TextToSpeak implements Runnable {
private Activity activity;
private static String text;
private static TextToSpeech talk;
public TextToSpeak(Activity activity, String toSpeak) {
this.activity = activity;
text = toSpeak;
}
public void run() {
talk = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
talk.setLanguage(Locale.UK);
}
}
});
talk.addEarcon("Attention", "com.kieronmc.aircraftgps", R.raw.warning_beep);
talk.playEarcon("Attention", QUEUE_ADD,null);
talk.setLanguage(Locale.UK);
talk.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
Try this code, It should work:
1) Create a text to speech Initializer as follows:
public class TextToSpeechInitializer{
private Context context;
private static TextToSpeech talk;
private TextToSpeechIniListener callback;
private Locale locale;
public TextToSpeechInitializer(Context context , Locale locale , TextToSpeechIniListener l) {
this.context = context;
if(l != null) {
callback = l;
}
this.locale = locale;
initialize();
}
private void initialize() {
talk = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
talk.setLanguage(locale); //TODO: Check if locale is available before setting.
callback.onSucces(talk);
}else{
callback.onFailure(talk);
Log.e("TTS","TextToSpeechInitializeError");
}
}
});
}
}
2) The above initializer class calls this interface class to notify the activity below (TTS Success or Failure) :
public interface TextToSpeechIniListener {
public void onSucces(TextToSpeech tts);
public void onFailure(TextToSpeech tts);
}
3) Activity
public class Demo7 extends AppCompatActivity implements TextToSpeechIniListener {
private Button b;
private TextToSpeechInitializer i;
private TextToSpeech talk;
private boolean flag = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo7);
i = new TextToSpeechInitializer(this, Locale.UK, this);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag) {
talk.addEarcon("Attention", getPackageName(), R.raw.androidcalm);
talk.playEarcon("Attention", QUEUE_ADD, null);
//talk.setLanguage(Locale.UK);
talk.speak("Hello, Testing", QUEUE_ADD, null);
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(talk != null){
talk.stop();
talk.shutdown();
}
}
#Override
public void onSucces(TextToSpeech tts) {
this.talk = tts;
flag = true;
}
#Override
public void onFailure(TextToSpeech tts) {
flag = false;
finish();
}
}
layout demo7.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/b"
android:text="speak"/>
</LinearLayout>
I have Android module library which will create the Touch Keypad UI and set event listener for done and backbutton.
Also have main activity with implement eventCallback interface
MainActivity.java (Appication)
public class MainActivity extends AppCompatActivity implements eventCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = new touchkey(this);
setContentView(v);
}
#Override
public void onClick() {
Log.i("test","complete");
Toast.makeText(this, "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
}
eventCallback.java (Android Module Library)
public interface eventCallback {
void onClick();
}
touchkey.java (Android Module Library)
public class touchkey extends RelativeLayout{
private static touchkey INSTANCE;
TextView bclear;
ImageView bdone;
eventCallback eventCall;
public touchkey(Context context) {
super(context);
initialize(context);
}
public touchkey(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public void test() {
Log.i("test","test");
}
private void initialize(Context context) {
inflate(context, R.layout.touchkey, this);
bclear = (TextView) findViewById(R.id.anti_theft_t9_key_clear);
bdone = (ImageView) findViewById(R.id.anti_theft_t9_key_done);
bdone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (eventCall != null) {
eventCall.onClick();
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
but iam getting nullpointer exception on the touchkey.java
eventCall.onClick(); (eventCall is null)
I dont know where i am doing things wrong. can anybody help on this. Requirement: i need to handle the click event happening on the Library in Main Activity
You must create setter for eventCall (in touchkey.java):
public void setEventCall(eventCallback eventCall) {
this.eventCall = eventCall;
}
And, use it (in MainActivity):
View v = new touchkey(this);
setContentView(v);
((touchkey) v).setEventCall(this);
I am testing an Android application. Currently I am writing tests for MainActivity. There are some dialogs that get opened when an item from options menu gets selected:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
new DialogCredits(this).show();
return true;
/.../
}
I would like to test if the dialog was successfully opened from JUnit testcase. My current test code looks like this:
public class MainActivityFunctionalTest extends
ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity activity;
private #Mock MenuItem item;
public MainActivityFunctionalTest() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
MockitoAnnotations.initMocks(this);
setActivityInitialTouchMode(false);
activity = getActivity();
}
#SmallTest
public void testOnOptionsItemSelected() {
when(item.getItemId()).thenReturn(android.R.id.home);
assertTrue(activity.onOptionsItemSelected(item));
// verify that the correct dialog was successfully opened
// --->code missing here<---
}
}
The code of DialogCredits class:
public class DialogCredits extends Dialog{
public DialogCredits(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.dialog_credits_title);
setContentView(R.layout.dialog_credits);
final Dialog d = this;
Button buttonOk = (Button) findViewById(R.id.dialog_credits_button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// close dialog
d.dismiss();
}
});
}
}
Try out Robotium, much less code and better methods like waitForDialog().
Well i had the same problem.
What i did was:
private YourDialog mDialog;
onCreate :
initDialog();
public void initDialog() {
mDialog = new YourDialog (this)
enter code here
}
public boolean isDialogShowing() {
return mDialog.isVisible();
}
Well, you must keep reference to the dialog so you can check is visibilty,
If you create new one all the time you will lose the last dialog ref.
DialogCredits dialog = new DialogCredits(this);
if(!dialog.isShowing())
{
dialog.show();
}
put this code in switch case