kill() mechanism, using existing API provided by the SDK. Manage your thread creation within a threadpool, and use Future. cancel() to kill the running thread: ExecutorService executorService = Executors.
Stopping a service. You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service. A service can terminate itself by calling the stopSelf() method.
A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.
To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once you've created a Handler , you can then use the post(Runnable) method to run a block of code in the corresponding thread.
I am trying to establish a runnable which can load ads by every 5 sec interval (of course 5 sec is too fast, it's just for testing purpose)
Here is my code:
package com.admobsdk_dfp_handler;
import com.google.ads.*;
import com.google.ads.doubleclick.*;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.widget.RelativeLayout;
public class AdMobSDK_DFP_Handler extends Activity {
private DfpAdView adView;
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
adView.loadAd(new AdRequest());
handler.postDelayed(this, 5000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ad_mob_sdk__dfp__handler);
adView = new DfpAdView(
this,
AdSize.BANNER,
AD_UNIT_ID);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.mainLayout);
layout.addView(adView);
adView.loadAd(new AdRequest());
handler.postDelayed(runnable, 5000);
};
@Override
protected void onDestroy() {
handler.removeCallbacks(runnable);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_ad_mob_sdk__dfp__handler,
menu);
return true;
}
}
If I press home button to hide the app to the background, the runnable keeps loading ads by 5 sec interval.
Is there any method to stop runnable when an app is hidden to the background? Many thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With