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();
}
});
Related
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);
}
}
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 this app which parses SMS and then converts them into Audio. My app users usually minimize the app and runs it all the time. But my app is getting terminated after sometime. How can i make sure my app will run till a user "terminates" it. Since the core functionality of the app is to convert SMS to audio, i need it running all the time.How can i do this ?
My current MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txtGateway, txtTime, txtAmount;
Speakerbox speakerbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textView = findViewById(R.id.txt_message);
speakerbox = new Speakerbox(getApplication());
txtAmount = findViewById(R.id.tv_amount);
txtGateway = findViewById(R.id.tv_gateway);
txtTime = findViewById(R.id.tv_time);
requestSmsPermission();
}
#Override
public void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onResume();
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onPause();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("otp")) {
final String message = intent.getStringExtra("message");
String gateway = intent.getStringExtra("gateway");
String time = intent.getStringExtra("time");
String amount = intent.getStringExtra("amount");
speakerbox.play(message);
txtGateway.setText(gateway);
txtTime.setText(time);
txtAmount.setText(amount);
// message is the fetching OTP
}
}
};
/**
* Requesting multiple permissions (storage and location) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestSmsPermission() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.SEND_SMS,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
// Toast.makeText(getApplicationContext(), "All permissions are granted!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
}
Use a foreground service to ensure that your app is not killed by Android. On newer version of Android, app's background process gets killed after sometime. Having a foreground service will ensure that your app stays active. Keep the service on background thread and not on the main thread.
Read more at:
https://developer.android.com/guide/components/services
and
https://androidwave.com/foreground-service-android-example/
Activities are used for user facing parts of your application. Use service instead. Most likely, your application is getting terminated by os due to low memory situation.
Use service for the core functionality if you want to run all the time in background.If user is not using your app actively yet app is taking RAM memory then OS will terminate the app to avoid out of memory.
I am using Scheduler to show 1 interstitial ad after every 60 seconds. But the problem is when user press Home or Menu button or minimize the app, or exit app by pressing back button the Interstitial ads are still displaying. I want to pause ads when application is minimized. Can anyone help....! please...
private InterstitialAd mInterstitialAd;
prepareAd();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i("hello", "world");
runOnUiThread(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", " Interstitial not loaded");
}
prepareAd();
}
});
}
}, 1, 60, TimeUnit.SECONDS);
}
public void prepareAd() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstitial));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
onPause();
}
}
I have a chat application and I want my GCM Broadcast to activate only when the phonescreen is locked or the app is not active (home button, not app killed!)
I tried the following:
boolean receiver_working = false;
public void enableBroadcastReceiver(){
IntentFilter filter = new IntentFilter();
filter.addAction("com.google.android.c2dm.intent.RECEIVE");
filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
filter.addCategory("com.flipflopdev.epvp_aj1987_chat");
registerReceiver(new GcmBroadcastReceiver(), filter);
Toast.makeText(getApplicationContext(), "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
receiver_working = true;
}
public void disableBroadcastReceiver(){
ComponentName receiver = new ComponentName(getApplicationContext(), GcmBroadcastReceiver.class);
PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
receiver_working = false;
}
#Override
public void onDestroy() {
super.onDestroy();
if(receiver_working) {
disableBroadcastReceiver();
}
}
#Override
public void onPause() {
super.onPause();
if(!receiver_working) {
enableBroadcastReceiver();
}
}
#Override
public void onResume() {
super.onResume();
checkPlayServices();
if(receiver_working) {
disableBroadcastReceiver();
}
}
The problem is that onResume() is firing even the activity just starts, thats why I have the boolean variable. When I leave the app now through home button, the GCM Notifications fire up like they should (because BR is activated), when I come back into the app it says BR deactivated but notifications still fire up if send.
Where is my mistake?