Prevent ads from showing in background (Android Studio) - java

so iv'e set my ad to show after every 5 minutes but the problem is that my app shows Ad even after my app is in background and i am using another app or just like keep the app at background.
I want my app Ads to stop showing after i put the app on background (My Ads don't show after i close app which is fine, but in background it still does)
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347551713");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940255099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
prepareAD();
ScheduledExecutorService ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ad not loaded");
}
prepareAD();
}
});
}
}, 5, 5, TimeUnit.MINUTES);
}else{
Toast.makeText(getApplicationContext(), "No Internet Connection, please try again later...", Toast.LENGTH_LONG).show();
}
}
public void prepareAD() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173212");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}

I will suggest to showing the app in the main thread instead of some background thread. If you pass anything to check if the activity is alive inside the background thread then it has chances of memory leak.
Even if it's in the background then it will check for the activity state and will fail.
getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
using the life cycle component, do this.
ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
boolean stateAlive = getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
if (stateAlive && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ad not loaded");
}
prepareAD();
}
});
}
}, 5, 5, TimeUnit.MINUTES);

Related

Set a delay of some seconds before reloading an interstitial ad

I want to set/add a delay when reloading an ad when it has failed to load. I think it could be done with Looper.getMainLooper() but I don´t know how to do this. You can see I have implemented that if the ad fails to load,it will be reloaded up to 5 times, so I think that adding a delay before reloading the ad could be a good option.
Here is my code:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
/*HERE IS WHERE THE AD IS RELOADED, SO THE DELAY COULD BE SET HERE BEFORE
CALLING THE REQUEST NEW INTERSTITIAL FUNCTION*/
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
I tried to do this.
if (maxRetry>0){
//add a delay before retrying
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestNewInterstitial(maxRetry-1);
}
}, 1000);
}
Hope this fixes your problem.
You can use a simple Handler to delay a function like this:
(Kotlin version, but you get the idea)
private fun reloadInterstitialAd() {
if (maxRetry > 0) {
val delayTime = 5000L // 5 seconds.
val looper = mainLooper // Use `Looper.getMainLooper()` if you do not have access to an Activity context.
mInterstitialAd = null
Handler(looper).postDelayed({
maxRetry--
requestNewInterstitial(maxRetry)
}, delayTime)
} else {
Log.d(TAG, "Max reload reached")
}
}
Use this function like reloadInterstitialAd() in the onAdFailedToLoad callback.
You can use this
Thread.sleep(delay_time_in_milliseconds);

Why does Interstitial Ads return me back to the home page?

I've made an webview app. I added interstitial ad on a regular interval. suppose after 120 seconds. When I close the interstitial Ad it take me back to the home page. Suppose I am browsing ABOUT Page. After close the ad it takes me back to the home page. But I want to stay in ABOUT page.
Main Activity.Java
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prepareAd();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i("Sample", "CV");
runOnUiThread(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", " Interstitial not loaded");
}
prepareAd();
}
});
}
}, 20, 40, TimeUnit.SECONDS);
}
public void prepareAd() {

android show Admob or Appodeal ads in service

I want to show admob or appodeal ads in service and app wont be shown in the recent apps.
I have tried many ways but didn't work.
I found this way but the app will come in recent apps!
‌‌‌‌‌‌‌‌‌‌‌‌
‌‌‌
public class ServiceAd extends Service {
private InterstitialAd mInterstitialAd;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mInterstitialAd = new InterstitialAd(getApplicationContext());
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
Log.d("tag", "on closed ad");
}
});
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("tag", "The interstitial wasn't loaded yet.");
}
}
}, 5000); // 5 mins
return START_STICKY;
}
}

Pause the changing Images when Audio paused

I am building an application in which images starts changing when audio is played.
When audio is play (starts) onclick button, the images also start changing with different delays and i can pause my audio as well. The problem which i am facing and getting confuse is that, when i paused my audio,
How can i pause my images as well ,so that when i click the button again,my audio resumes and images starts changing next from where they were paused.
private Button btn_play;
MediaPlayer mp;
int duration;
private ImageView imageView;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_names);
int resID = getResources().getIdentifier("audio", "raw", getPackageName());
mp = MediaPlayer.create(NamesOfALLAH.this, resID);
duration = mp.getDuration();
btn_play = (Button) findViewById(R.id.btn_play);
imageView = (ImageView) findViewById(R.id.imageView_Names);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
btn_play.setText("Play");
} else {
mp.start();
btn_play.setText("Pause");
changeImage1();
changeImage2();
changeImage3();
changeImage4();
changeImage5();
}
}
});
}
public void changeImage1() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a1);
}
}, 6000);
}
public void changeImage2() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a2);
}
}, 8000);
}
public void changeImage3() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a3);
}
}, 10000);
}
public void changeImage4() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a4);
}
}, 11000);
}
public void changeImage5() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageResource(R.drawable.a5);
}
}, 12000);
}
`
Use an ImageSwitcher, it does some of the work for you. In any case, if you want to create the animation yourself, you must consider all the changes as a whole. For example, you can repost the runnable to the handler. Pseudo-code:
handler.postDelayed(new Runnable() {
#Override
public void run() {
// set the image you want
if (mustContinue)
handler.postDelayed(this, time);
}
}, 10000);
Toggle the boolean mustContinue every time you press the play/pause button.
EDIT:
Check this as an example.

I want Android progress dialog to stay on screen until function on new activity is complete but doesn't work

In my Android app, one form has a button which upon click opens up another; the new form performs activities which can take a while. I want the first form to remain open and for the progress dialog to keep spinning while these activities finish.
I've attempted this below, but it just won't work. The progress dialog just finishes and opens up the next window (before described activities on new form have finished)
In the below code SecondForm -
The subroutine "Calculations", is what takes a while to complete
Code:
MainActivity:
final ProgressDialog ringProgressDialog = new ProgressDialog(
MainActivity.this);
ringProgressDialog.setTitle("Loading");
ringProgressDialog.show();
ringProgressDialog.setCancelable(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(
getApplicationContext(),
SecondForm.class);
startActivity(intent);
}
});
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
SecondForm:
public class CategoryTabs extends Fragment {
static Context mContext;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
gotstatdata = false;
rootView = inflater.inflate(R.layout.fragment_abc, container, false);
mContext = rootView.getContext();
new Thread(new Runnable() {
#Override
public void run() {
try {
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
gotstatdata = false;
Calculations(128);
gotstatdata = true;
}
});
} catch (Exception e) {
}
}
}).start();
You are dismissing your dialog as soon as it runs with ringProgressDialog.dismiss();.
That line should be removed and you should do something like send out a broadcast when you are finished to close the progress dialog.
It looks like you might also just want a background thread rather than a second Activity because no user interaction is required.
Looking at AsyncTask would be the easiest way for you to start with background threads and it's 'onPostExecute` method will allow you to dismiss your dialog.
Edit
The basic structure you want is to add the following
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO: show your dialog from here
}
#Override
protected Void doInBackground(Void... params) {
//TODO: call Calculations(128); from here
//Calculations(128); should live within this async task instead of a new activity
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO: call dismiss on your dialog from here
}
}.execute();
instead of the new Thread(new Runnable() { block you currently have

Categories

Resources