I'm in need of help, I'd like to display an interstitial add after the splash screen screen loads, but my code has an error.
Here is my code:
public class SplashScreenActivity extends AppCompatActivity {
InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// FIREBASE INTERSTICIAL
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-2565065222479596/3931476543");
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
Toast.makeText(this,"* Necessário Acesso a Internet *",Toast.LENGTH_LONG).show();
Thread timerThread = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
}
}
}
};
timerThread.start();
}
// FIREBASE INTERSTICIAL
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
mInterstitialAd.loadAd(adRequest);
}
}
after debugging the following is informed:
01-22 16:27:03.048 13840-13970/? E/AndroidRuntime: FATAL EXCEPTION: Thread-6
Process: idea.tisco.pepavideos, PID: 13840
java.lang.IllegalStateException: isLoaded must be called on the main UI thread.
at oc.b(:com.google.android.gms.DynamiteModulesA#11951448:20)
at com.google.android.gms.ads.internal.a.d(:com.google.android.gms.DynamiteModulesA#11951448:98)
at com.google.android.gms.ads.internal.client.ak.onTransact(:com.google.android.gms.DynamiteModulesA#11951448:14)
at android.os.Binder.transact(Binder.java:499)
at com.google.android.gms.internal.zzep$zza$zza.isReady(Unknown Source)
at com.google.android.gms.internal.zzfa.isLoaded(Unknown Source)
at com.google.android.gms.ads.InterstitialAd.isLoaded(Unknown Source)
at company.ts.SplashScreenActivity$2.run(SplashScreenActivity.java:50)
Even after the debug I could not understand the reason for the error.
I would like to just display an interstitial just after the splash screen or when I open the mainactivity.
Thank you so much!
the problem is herejava.lang.IllegalStateException: isLoaded must be called on the main UI thread.
so may have to do this
runOnUiThread(new Runnable() {
#Override public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
Possibly You have to call it with an activity reference, it depends from where Do You call
mYourActivity.runOnUiThread(new Runnable() {
#Override public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
Source:AdMob Interstitial and error isLoaded must be called on the main UI thread
Facebook Interstitial Ads on Splash Screen.
Build.Gradle :
implementation 'com.facebook.android:audience-network-sdk:5.+'
implementation 'com.victor:lib:1.0.4'
MyAplication.java:
AudienceNetworkAds.initialize(this);
Manifest.xml:
<activity
android:name="com.facebook.ads.AudienceNetworkActivity"
android:configChanges="keyboardHidden|orientation|screenSize" />
Permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
activity_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_light"
tools:context=".SplashActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#android:color/background_light"
android:text="Splash Screen"
android:textSize="25sp"
android:layout_marginTop="20dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/loadingTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Loading Ad..."
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp"
android:textColor="#android:color/holo_red_dark"/>
<com.victor.loading.rotate.RotateLoading
android:id="#+id/rotateloading"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_above="#+id/loadingTxt"
app:loading_color="#android:color/holo_red_dark"
android:layout_centerHorizontal="true"
app:loading_speed="11"
app:loading_width="5dp" />
</RelativeLayout>
SplashActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.InterstitialAd;
import com.facebook.ads.InterstitialAdListener;
import com.victor.loading.rotate.RotateLoading;
import java.lang.ref.WeakReference;
public class SplashActivity extends AppCompatActivity {
private Handler handler;
private SplashThread splashThread;
private InterstitialAd facebookInterstitialAd;
private boolean isAdsLoad=false;
private TextView loadingTxt;
private RotateLoading rotateloading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
loadingTxt=(TextView)findViewById(R.id.loadingTxt);
rotateloading=(RotateLoading)findViewById(R.id.rotateloading);
if (isNetworkAvailable(this)){
//if on then load ads
rotateloading.start();
handler=new Handler();
splashThread=new SplashThread(this);
handler.postDelayed(splashThread,5000); //5 second delay otherwise ads not show it take some time to load
loadFaceBookAds();
}
else{
//if network off then show simple splash screen
rotateloading.setVisibility(View.GONE);
loadingTxt.setVisibility(View.GONE);
handler=new Handler();
splashThread=new SplashThread(this);
handler.postDelayed(splashThread,2000); //2 second delay for simple splash
}
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != connectivity) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
private void loadFaceBookAds(){
facebookInterstitialAd=new InterstitialAd(this,"Facebook_Interstitial_Ads_ID");
facebookInterstitialAd.setAdListener(new InterstitialAdListener() {
#Override
public void onInterstitialDisplayed(Ad ad) {
}
#Override
public void onInterstitialDismissed(Ad ad) {
//on dismiss ads call next activity
finish();
startActivity(new Intent(SplashActivity.this,MainActivity.class));
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
//if ads load then show it.
isAdsLoad=true;
rotateloading.stop();
rotateloading.setVisibility(View.GONE);
loadingTxt.setVisibility(View.GONE);
facebookInterstitialAd.show();
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onLoggingImpression(Ad ad) {
}
});
facebookInterstitialAd.loadAd();
}
static class SplashThread implements Runnable{
//Handle memory leakage..
WeakReference<SplashActivity> weakReference;
SplashThread(SplashActivity splashActivity){
weakReference=new WeakReference<>(splashActivity);
}
#Override
public void run() {
SplashActivity mContext=weakReference.get();
if (mContext==null)
return;
if (mContext.isFinishing())
return;
//if ads loaded no need to call next activity here.
if (!mContext.isAdsLoad) {
if (mContext.rotateloading.getVisibility()==View.VISIBLE) {
mContext.rotateloading.stop();
mContext.rotateloading.setVisibility(View.GONE);
}
mContext.finish();
mContext.startActivity(new Intent(mContext, MainActivity.class));
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(splashThread);
if (facebookInterstitialAd!=null)
facebookInterstitialAd.destroy();
}
}
This is the simplest method ever existed on the internet.
add bellow code in your onCreate method of Splash activity.
InterstitialAd ad;
ad = new InterstitialAd(this);
ad.setAdUnitId(getString(R.string.interstitial));
ad.loadAd(new AdRequest.Builder().build());
ad.setAdListener(new AdListener(){
#Override
public void onAdClosed() {
super.onAdClosed();
startActivity(new Intent(getApplicationContext(), PermissionsActivity.class));
finish();
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(ad.isLoaded()) {
ad.show();
}
else{
startActivity(new Intent(getApplicationContext(), PermissionsActivity.class));
finish();
}
}
}, 4000);
Related
Android Webview
current code in my app works like this:
When user press back single time it will shows button asking "Do you want to quit?" shows yes or no options. when we select Yes it exit app and show interstitial ad. if you press No it will remains in the activity.
What I want is:
When user press back it will go to previous activity. If user double tap back button then it will ask for exit and if user select Yes. user will exit app and interstitial ad appears.
Please help me to solve this issue.
Main Activity:
public class MainActivity extends Activity{
private Fragment contentFragment;
String testDevice = "D0A04359EA1ECE9BA0CD4B6F457A9991";
String testDevice2 = "63C3530DA03C191310DB9AB8F0672E5C";
String testDevice3 = "801F2141A1DC3F743363AFDFDC42AF3A";
private InterstitialAd mInterstitialAd;
private AdView mAdView;
boolean displayAd = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mainWebView.loadUrl(this.getString(R.string.channel_url));
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.build();
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayAd = true;
// View servername = findViewById(R.id.txt_List);
// RelativeLayout.LayoutParams layoutparams =
(RelativeLayout.LayoutParams) servername.getLayoutParams();
// layoutparams.addRule(RelativeLayout.BELOW, mAdView.getId());
// layoutparams.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
// servername.setLayoutParams(layoutparams);
}
#Override
public void onAdFailedToLoad(int errorCode) {
if (!displayAd) {
}
}
#Override
public void onAdClosed() {
// Proceed to the next level.
}
});
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
// Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).
mInterstitialAd = newInterstitialAd();
loadInterstitial();
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private InterstitialAd newInterstitialAd() {
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
// Proceed to the next level.
finish();
//goToNextLevel();
}
});
return interstitialAd;
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(testDevice)
.addTestDevice(testDevice2)
.addTestDevice(testDevice3)
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof EmpListFragment or if the stack entry count is == 0, then
* we prompt the user whether to quit the app or not by displaying dialog.
* In other words, from EmpListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
onShowQuitDialog();
}
public void onShowQuitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do You Want To Quit?");
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
showInterstitial();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
This is the easiest code possible:
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onBackPressed() {
if (back_pressed + TIME_DELAY > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Press once again to exit!",
Toast.LENGTH_SHORT).show();
}
back_pressed = System.currentTimeMillis();
}
}
A temp flag will do the thing.
add this code in your onBackPressed() method.
boolean isSecond;
#Override
public void onBackPressed(){
if (isSecond) {
// Open your dialog here
}
isSecond = true;
new Handler() . postDelayed(new Runnable() {
#Override
public void run(){
isSecond = false;
}
}, 2000);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
onShowQuitDialog();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Try following code :
int backFlag = 0;
#Override
public void onBackPressed() {
backFlag ++;
if(backflag == 1){
super.onBackPressed();
// go to previous activity
}
else if(backFlag == 2){
// ask user to exit
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
backFlag=0;
}
}, 2000);
}
There is no built-in function for double onBackPressed() so you have to construct your own version of it. The android system provides a Handler on which you can call postDelayed to measure the time between two and one click.
e.g. like this
boolean backPressed = false;
boolean backPressedTwice = false;
#Override
public void onBackPressed() {
if(!backPressed){
backPressed = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(!backPressedTwice)
MainActivity.this.finish(); // go back to previous activity
}
}, 500);
}
if(backPressed) {
// it's clicked twice
backPressedTwice = true; // cancel the handler so it does not finish the activity
onShowQuitDialog();
}
}
Demo for your task:
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler();
boolean ShowDialog = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(getMainLooper());
}
#Override
public void onBackPressed() {
if (!ShowDialog) {
this.ShowDialog = true;
handler.postDelayed(runnable, 2000);// time setting .. current is 2 sec
} else {
handler.removeCallbacks(runnable);
ShowDialog = false;
ShowDailog();
}
}
private void ShowDailog() {
Toast.makeText(this, "show dialog here", Toast.LENGTH_LONG).show();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
ShowDialog = false;
MainActivity.super.onBackPressed();
}
};
}
You can do something like this
private long backPressedTime = 0;
private long backPressThreshold = 400;
private Handler mHandler = new Handler();
private Runnable bacPressedRunnable = new Runnable() {
#Override
public void run() {
MYActivity.super.onBackPressed();
}
};
#Override
public void onBackPressed() {
if(backPressedTime = 0){
backPressedTime = Systemm.currentTimeInMillis();
mHandler.postDelayed(bacPressedRunnable,backPressThreshold);
}else if(System.currentTimeInMillis()-backPressedTime >= backPressThreshold){
mHandler.removeMessages(bacPressedRunnable);
onShowQuitDialog();
}else{
super.onBackPressed();
}
backPressedTime = 0;
}
Exit android App on double back press use following updated code. It may solve your problem
private boolean doubleBackToExitPressedOnce;
private void onApplicationBackPressed() {
if (doubleBackToExit) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
return;
}
doubleBackToExit= true;
Utilities_dialer.showToastMessage(this, "Press Again To Exit");
//use your dialog box or toast message
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit= false;
}
}, 2000);
}
Try this.. It may help you.
Boolean doubleBackToExitPressedOnce = true;
#Override
public void onBackPressed() {
if(doubleBackToExitPressedOnce){
// Do what ever you want
doubleBackToExitPressedOnce = false;
} else{
// Do exit app or back press here
super.onBackPressed();
}
}
I have implemented a Splash Screen on an android app I am building using Android Studio and I would like to add a spinner to the splash screen. Can anyone give me a hand on this:
Here is the code on my splashScreen.java Class:
package com.packagename.appname;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
/**
* Created by VAIO1 on 05/09/2014.
*/
public class splashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(3000);
Intent splashIntent = new Intent("com.packagename.appname.SPLASH");
startActivity(splashIntent);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
finish();
}
}
};
logoTimer.start();
}
#Override
protected void onPause() {
super.onPause();
}
}
Here is the code for my splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/splashId">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:src="#drawable/screen"
android:cropToPadding="false"
android:scaleType="fitXY"/>
</LinearLayout>
Thank you for any feedback on how to achieve this.
use this code :-
public class splashScreen extends Activity {
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(3000);
progressDialog = new ProgressDialog(Sync_Screen_activity.this);
progressDialog.setMessage("Wait..");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent splashIntent = new Intent("com.packagename.appname.SPLASH");
startActivity(splashIntent);
finish();
}
}
};
logoTimer.start();
}
#Override
protected void onPause() {
super.onPause();
}
}
I've got an app that displays an Interstitial Ad when certain activity is closed. I use a different activity to show the Ad. So far it shows the Ad correctly but nothing happens when I click on the Ad. I've tested it on many devices and beta testers report the same behavior. There are no errors in the logs. It's the same if I use debug build or signed APK that is uploaded to the play store (it's published in alpha state if it matters). I use the latest Play Store Services SDK.
What could be the reason for this?
My activity that shows the Ad (I use the correct unit id in the actual code)
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class AdFullScreen extends Activity {
private static final String TAG = "AdFullScreen";
private static final String AD_UNIT_ID = "my-unit-id";
private InterstitialAd interstitialAd;
ProgressBar prgrssBrAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ad_layout);
prgrssBrAd = (ProgressBar) findViewById(R.id.prgrssBrAd);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.e(TAG, "onAdLoaded");
prgrssBrAd.setVisibility(View.GONE);
if (interstitialAd.isLoaded()) {
interstitialAd.show();
} else {
Log.e(TAG, "Interstitial ad was not ready to be shown.");
finish();
return;
}
}
#Override
public void onAdFailedToLoad(int errorCode) {
String message = String.format("onAdFailedToLoad (%s)",
getErrorReason(errorCode));
Log.e(TAG, message);
finish();
return;
}
#Override
public void onAdClosed() {
finish();
return;
}
#Override
public void onAdLeftApplication() {
Log.e(TAG, "onAdLeftApplication");
finish();
return;
}
});
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager
.getLastKnownLocation(locationProvider);
if (lastKnownLocation == null) {
locationProvider = LocationManager.NETWORK_PROVIDER;
lastKnownLocation = locationManager
.getLastKnownLocation(locationProvider);
Log.e(TAG, "Last location not available by GPS");
} else {
Log.e(TAG, "Last location available by GPS");
}
// Check the logcat output for your hashed device ID to get test ads on
// a physical device.
AdRequest.Builder bldr = new AdRequest.Builder();
if (lastKnownLocation != null) {
Log.e(TAG, "Last location available");
bldr.setLocation(lastKnownLocation);
} else {
Log.e(TAG, "Last location not available by any provider");
}
AdRequest adRequest = bldr.build();
// Load the interstitial ad.
interstitialAd.loadAd(adRequest);
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
}
/** Gets a string error reason from an error code. */
private String getErrorReason(int errorCode) {
String errorReason = "";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
}
The layout (I've tried to not use any layouts with same results).
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ProgressBar
android:id="#+id/prgrssBrAd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
I would appreciate any help you can provide.
UPDATE
It seems that I managed to find the problem. It was related to the AndroidManifest configuration:
Old one, Ads are not clickable:
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:launchMode="singleInstance" />
Good one, works fine:
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
Sorry for the confusion, I cant recall when I did that change.
it will work definitely
public class AdFullScreen extends Activity implements AdListener {
private InterstitialAd interstitial;
private String MY_INTERSTITIAL_UNIT_ID = "your unit id here";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ad_layout);
interstitial = new InterstitialAd(this, MY_INTERSTITIAL_UNIT_ID);
// Create ad request
AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
// Set Ad Listener to use the callbacks below
interstitial.setAdListener((AdListener) this);
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad add) {
// TODO Auto-generated method stub
if (add == interstitial) {
interstitial.show();
}
}
This code is homepage of my app. For this app i want to create splash .
main app code:-
package com.Wase.edittext;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.widget.EditText;
public class Splash extends Activity {
Timer timer = new Timer();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_logo);
Time.schedule(new TimerTask() {
public void run() {
Intent intent = new Intent(Splash.this, MyAndroidAppActivity.class);
startActivity(intent);
finish();
}
}, 5000);
}
}
This my code for splash.. please see the mistake amd tell me ..
First of all create one new XML file and use whatever design you want and after that create activity (java) file and use below code and change your screen and variable name as per your requirement.
public class Splash extends Activity {
Timer timer = new Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
timer.schedule(new TimerTask() {
public void run() {
Intent intent = new Intent(Splash.this, MyAndroidAppActivity.class);
startActivity(intent);
finish();
}
}, 5000);
}
}
and this is your splash.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
tools:context=".IMyCompany" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="153dp"
android:src="#drawable/logo" />
</RelativeLayout>
it will move to new activity after 5 seconds.
public class SplashScreen extends Activity {
public SplashScreen instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_splashscreen);
if (instance != null) {
instance.finish();
}
instance = this;
Thread threadMenu = new Thread(new Runnable() {
public void run() {
try {
// sleep 3 second and go next page
Thread.sleep(400);
// Check Vefication Success then Load HomeScreen Check
Intent splash = new Intent(getBaseContext(),
MyAndroidAppActivity .class);
startActivity(splash);
finish();
overridePendingTransition(R.anim.push_in_from_left,
R.anim.push_out_to_right);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadMenu.start();
}
}
in manifest file :
<activity
android:name="com.demo.SplashScreen"
android:label="#string/app_name"
android:screenOrientation="sensorPortait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".com.demo.MyAndroidAppActivity"
android:configChanges="keyboardHidden"
android:screenOrientation="sensorPortait"
android:windowSoftInputMode="stateHidden" />
use this code
====
public class SplashScreenActivity extends Activity {
final int splashTimeOut = 3000;
ImageView imgSplash;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
imgSplash = (ImageView) findViewById(R.id.imgsplash);
setContentBasedOnLayout();
// TODO Auto-generated method stub
Thread splashThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
while (wait < splashTimeOut) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//If You Want To Do Something Write Here Your Code
}
}
};
splashThread.start();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I want to write a code that uses the splash screen .I have written this so far, but Can anyone tell me what is the missing here!?
here is my main code:
package com.example.splash;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
and here is my splash activity code:
package com.example.splash;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class splashscreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashh);
final splashscreen sPlashScreen = this;
splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
finish();
Intent i = new Intent();
i.setClass(sPlashScreen,MainActivity.class);
startActivity(i);
//stop();
}
}
};
splashTread.start();
}
The problem is I do not know how to tell my main to go splash activity , if I use an intent I would stuck on infinite loop.
You can simply use this:
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashViewController.this,HomeViewController.class);
startActivity(intent);
SplashViewController.this.finish();
}
}, 3000);
try this instead :
public class splashscreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
Thread t = new Thread(Splash_Runnable);
t.start();
}
Runnable Splash_Runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3000);
startActivity(new Intent(splashscreen.this,
MainActivity.class));
splashscreen.this.finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
The problem (i guess) is that your app is starting with your MainActivity as your launcher Activity. Make splashscreen your laucher Activity in your Application Manifest XML and you will avoid the infinite loop.
Try this code:
private boolean _active = true;
private int _splashTime = 5000;
Thread splashTread = new Thread()
{
#Override
public void run()
{
try
{
int waited = 0;
while(_active && (waited < _splashTime))
{
sleep(100);
if(_active)
{
waited += 100;
}
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(SplashScreenActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
};
splashTread.start();
in AndroidManifest mention your activity as Main Activity.
Try to change your SplashActivity code from here.
Splash and main activity error
Also make your splashactivtiy as your launcher activity and then redirect to the MainActivity from the SplashScreen
<activity
android:name="com.app.wablogic.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
Full detail of creating a splash Activity
Create a layout for Splash
splash.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:orientation="vertical"
android:background="#drawable/splash" >
</LinearLayout>
Now create a class Under package . Name it Splash
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent openMainActivity = new Intent(Splash.this, MainActivity.class);
startActivity(openMainActivity);
finish();
}
}, 5000); //it will call the MainActivity after 5 seconds
}
Go to manifest and add the Activity to it.
and cut the intent-filter where main and Launcher are child and paste it in Splash Activity like
<activity
android:name="com.example.yourpackage.Splash"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You can create a Thread for doing something or just sleep for a few seconds to do, such as
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 3 seconds
sleep(3*1000);
// After 3 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),MenuActivity.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
background.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
You can get more example here.