AdMob interstitial Ad is shown but can't click on it - android

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();
}
}

Related

How to show interstitial ad after loading the splash screen?

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);

Integrating of Analytics doesn´t work

I try to integrate google Analytics to my Application but it doesn´t work.
This is my Activity:
public class InhaltsverzeichnisActivity extends Activity {
private SharedPreferencesManager prefs; //added
private InterstitialAd Interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inhaltsverzeichnis);
prefs = new SharedPreferencesManager(this); //get SharedPreferencesManager instance
int t = prefs.retrieveInt("theme", 0); //get stored theme, zero is default
ThemeUtils.setTheme(t); //Set the stored theme, will default to Black
Tracker t1 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t1.setScreenName("Inhaltsverzeichnis");
t1.send(new HitBuilders.AppViewBuilder().build());
Interstitial = new InterstitialAd(this);
Interstitial.setAdUnitId("ca-app-pub-XXXXXXXXXXXXX/XXXXXXXXXX");
AdRequest adRequest = new AdRequest.Builder().build();
Interstitial.loadAd(adRequest);
;
Interstitial.setAdListener(new AdListener(){
public void onAdLoaded(){
displayInterstitial();
Interstitial.show();
}
});
}
protected void displayInterstitial() {
// TODO Auto-generated method stub
}
public void onDismissScreen() {
// TODO Auto-generated method stub
}
public void onFailedToReceiveAd() {
// TODO Auto-generated method stub
}
public void onLeaveApplication() {
// TODO Auto-generated method stub
}
public void onPresentScreen() {
// TODO Auto-generated method stub
}
#Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(InhaltsverzeichnisActivity.this).reportActivityStart(this);
}
#Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(InhaltsverzeichnisActivity.this).reportActivityStop(this);
}
If I put the OnStart and OnStop method over the Interstitial Ad , Analytics works, but the Interstitial Ad goes crazy and appears every second again,
hope anyone can help me to solve this problem thanks.

how to place ads in admob in app

how to use ad-mob in app and what are the steps how i post ads in ad-mob how can i test in my device before uploading to Google play store.i am new to ad-mob. please explain me with sample example of it by step-wise.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.interstitialAds = new InterstitialAd(this, "ca-app-pub-****");
this.interstitialAds.setAdListener(this);
Button loadButton = (Button) this.findViewById(R.id.loadButton);
loadButton.setOnClickListener(loadButtonOnClick);
this.textView = (TextView) this.findViewById(R.id.stateTextView);
}
private OnClickListener loadButtonOnClick = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText("Loading Intertitial Ads");
AdRequest adr = new AdRequest();
// add your test device here
adr.addTestDevice(AdRequest.TEST_EMULATOR);
interstitialAds.loadAd(adr);
}
};
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad ad, ErrorCode error) {
String message = "Load Ads Failed: (" + error + ")";
textView.setText(message);
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
/**
* Called when an Activity is created in front of the app (e.g. an
* interstitial is shown, or an ad is clicked and launches a new Activity).
*/
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad arg0) {
if (interstitialAds.isReady()) {
interstitialAds.show();
} else {
textView.setText("Interstitial ad was not ready to be shown.");
}
}
}
Get rid of your AdListener.
Call intersitial.loadAd in your constructor
Call interstitial.show at a natural break point in your app
Call interstitial.loadAd
Go to 3.
See https://developers.google.com/mobile-ads-sdk/docs/admob/android/interstitial

How to close activity without destroying it?

Ok so first, I have menu with 3 buttons leading to 3 different layouts.
What I want, I want to show interstitial ad when I close my application.
What happens, In order to save memory I had to add finish() on every button so it doesn't take all memory. And when I click on any button interstitial ad shows.
Whats the problem, I can't set my code to show interstitial only when I completely close app not when I switch activities
My code:
package puske.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.ads.*;
import com.google.ads.AdRequest.ErrorCode;
public class Menu extends Activity implements AdListener {
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
interstitial = new InterstitialAd(this, "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(this);
}
#Override
public void onReceiveAd(Ad ad) {
{
Button button1=(Button)findViewById(R.id.menu1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Menu.this, Rifles.class));
finish();
}
});
Button button2=(Button)findViewById(R.id.menu2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Menu.this, Pistols.class));
finish();
}
});
Button button4=(Button)findViewById(R.id.menu3);
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Menu.this, Snipers.class));
finish();
}
});
}
}
#Override
protected void onDestroy() {
interstitial.show();
super.onDestroy();
// explicitly release media player
unbindDrawables(findViewById(R.id.menuzor));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
try
{
((ViewGroup) view).removeAllViews();
}
catch(UnsupportedOperationException ignore)
{
}
}
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#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 onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
}
Look at this picture
onPause or onStop();
Just try

Google+ sign out from a different activity

I have started using the Google+ API for android, and I have created a sign-in application following this tutorial:
https://developers.google.com/+/mobile/android/sign-in
Now, the problem is that I want to create the sign out button from a different Activity, and what i tried to do didn't really worked..
My GPlusLogin code (Activity for the Google+ Login):
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
public class GPlusLogin extends Activity implements ConnectionCallbacks, OnConnectionFailedListener{
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private static final String TAG = "GPlusLogin";
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gplus_layout);
mPlusClient = new PlusClient.Builder(this, this, this).setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
Bundle extras = getIntent().getExtras();
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
if(extras!=null){
if(extras.getString("signout")!=null){
if (mPlusClient.isConnected()) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
mPlusClient.connect();
finish();
startActivity(getIntent());
}
}
}else{
findViewById(R.id.sign_in_button).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(GPlusLogin.this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
});
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
mConnectionResult = result;
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
public void onConnected() {
// TODO Auto-generated method stub
mConnectionProgressDialog.dismiss();
Intent main = new Intent(GPlusLogin.this, MainActivity.class);
main.putExtra("result", true);
startActivity(main);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
Log.d(TAG, "disconnected");
}
}
My Disconnect code on MainActivity:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if(extras==null){
Intent intent = new Intent(this, GPlusLogin.class);
startActivity(intent);
}
TextView text1 = (TextView) findViewById(R.id.text1);
text1.setText("You Are Connected :D");
Button SignOut = (Button) findViewById(R.id.sign_out_gplus);
SignOut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, GPlusLogin.class);
intent.putExtra("signout", true);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Just add this on your new activity, where you want your logout-button for google+ to be there :
#Override
protected void onStart() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleApiClient.connect();
super.onStart();
}
and next:
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// ...
Toast.makeText(getApplicationContext(),"Logged Out",Toast.LENGTH_SHORT).show();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
}
});
Hey i solved this problem by myself, working like charm
What is the problem : Google plus signIn in one activity but need to Logout from another activity
Solution:
My Google-plus Logout Activity is like this:
public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult> {
GoogleApiClient mGoogleApiClient;
boolean mSignInClicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
//copy this code on "Logout" Onclick
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// updateUI(false);
System.err.println("LOG OUT ^^^^^^^^^^^^^^^^^^^^ SUCESS");
}
}
});
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
mSignInClicked = false;
// updateUI(true);
Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(
this);
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
// updateUI(false);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onResult(LoadPeopleResult arg0) {
// TODO Auto-generated method stub
}
Description about solution:
For single package google plus API will generate one token & session.Just here simply make one more session in logout page also.You can easily logout from session now
I to have tried a lot about this problem,to logout from current session, just try this .it will definitely work. any doubts let me know
It would probably be easier to create a base class and inherit the connect/disconnect methods. Photohunt, our full sample, documents this design in detail.
Docs
Code
You can get instance of FirebaseAuth anywhere from the app as FirebaseAuth is a singleton class.
mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
After struggling for over a week to find out the answer.
I did this,
After signing in save boolean isSignedIn in sharedpreferences as true.
private SharedPreferences.Editor editor;
private SharedPreferences prefs;
editor = getSharedPreferences(getString(R.string.userDetails), MODE_PRIVATE).edit();
editor.putBoolean(getString(R.string.isSignedIn), true);
editor.apply();`
Now from any activity when the user clicks logout, change the boolean to false.
In your Login Activity where googleApiClient is build. In its onStart method.
Check if isSignedIn is false.
#Override
public void onStart() {
super.onStart();
if (!prefs.getBoolean(getString(R.string.isSignedIn), false)) {
signOut();
}
}
Do the same in onConnected
#Override
public void onConnected(Bundle connectionHint) {
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "onConnected: " + "yes it is connected");
if (!prefs.getBoolean(getString(R.string.isSignedIn), false)) {
signOut();
}
}
}
This will logout and revokeAccess.
public void signOut() {
if (mGoogleApiClient != null) {
Log.e(TAG, "signOut: " + mGoogleApiClient + mGoogleApiClient.isConnected());
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
if (mGoogleApiClient.isConnected()) {
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// ...
Log.i(TAG, "onResult: " + mGoogleApiClient);
}
});
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.i(TAG, "onResult: Revoke Access status:" + status.getStatus());
}
});
}
}
}
Once you click logout from another activity,try send an intent with extra to indicate that logout button is clicked. Then on Login Activity
if (Intent.Extras != null && Intent.Extras.ContainsKey("LogoutAction")) {
_logoutRequest = Intent.Extras.GetBoolean("LogoutAction");
}
if (_logoutRequest) {
await PlusClass.AccountApi.RevokeAccessAndDisconnect(_apiClient);
_apiClient.Disconnect();
_apiClient.Connect ();
_logoutRequest = false;
}
Other Activity
var intent = new Intent(this.Activity,typeof(LoginActivity));
intent.PutExtra("LogoutAction",true);
Jonathan is correct that a base class or a fragment would make your life easier. That said, the code here could work - the problem is that you're checking whether the PlusClient is connected in onCreate() - but you don't connect it until onStart(). You'd probably need to check the intent in the onConnected() method, and perform the sign out there.
sommesh's answer is perfect, but for less code you can use "Public Static Method" like this:
public static GoogleApiClient mGoogleApiClient;
...
...
public static void signOutFromGoogle() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
//...
}
});
}
And on your other Activity call it:
Your_Google_Activity.mGoogleApiClient.connect();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Your_Google_Activity.signOutFromGoogle();
}
});
Here's my solution. I have made a Utils singleton class. In my LoginActivity, I have a GoogleSignInClient object. So just before starting the DashboardActivity after login, I save the instance of googleSignInClient object by calling Utils.getInstance().setGoogleSignInClient(googleSignInClient). Now anywhere else, if I want to logout I have this method in Utils ready:
public void signOut() {
googleSignInClient.signOut();
FirebaseAuth.getInstance().signOut();
}
So now, I can do this from any other activity:
else if (id == R.id.action_logout) {
Utils.getInstance().signOut();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
Yes, you need to log out from both of them, otherwise, you might not see the account chooser the next time you tap the login button.

Categories

Resources