Why is there a delay between closing interstitial ad and opening the target activity? - android-activity

I implemented this android code to load and show an interstitial ad and after closing the ad it will open the target activity, but my problem is there's a 3 seconds delay between closing and opening the target activity...here's my code:
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(HomeActivity.this, UNIT_ID, adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
admobInterstitialAd = interstitialAd;
admobInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
admobInterstitialAd = null;
/**********Here is the delay when starting the activity for about 3 seconds*******/
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
/********************************************************************************/
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
admobInterstitialAd = null;
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
admobInterstitialAd = null;
}
});
if (admobInterstitialAd != null) {
admobInterstitialAd.show(HomeActivity.this);
}
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
admobInterstitialAd = null;
Intent intent = new Intent(HomeActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
Any suggestions to fix this issue....thanks in advance...

I faced the same problem. I still haven't been able to fix the problem and couldn't find a resource that does. While searching on Google, I realized that you are not alone and those who have the same problem on other platforms.
As a workaround, I will use a progress dialog. This makes users wait until the ad closes and the new event starts. I think 1-3 seconds.
if (mInterstitialAd != null) {
mInterstitialAd.show(MainAct.this);
startActivity(new Intent(MainAct.this, NewAct.class));
progressDialog.show();
} else {
startActivity(new Intent(MainAct.this, MafA.class));
}

Related

Pass data from android to flutter

I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,

Getting skipped frames with RxAndroid on a simple call

I'm implementing in a LauncherActivity (with just a loading indicator) an Observable (Single) from RxJava library to login with the previously recorded users credentials.
The activity is very very simple, and yet I get a skipped frames warning (40ish), both on my phone and on emulator, and I can't figure out why (though sometimes it doesn't show up).
Here is the code :
public class LauncherActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mProgressBar = findViewById(R.id.progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
if (UsersUtils.hasCredentialsRecorded(this)) {
getAccessToken();
} else {
login();
}
}
public void getAccessToken() {
Callable<Token> callable = new Callable<Token>() {
#Override
public Token call() throws Exception {
final Map<String, byte[]> credentials = UsersUtils.getCredentials(getApplicationContext());
Token token = OauthCalls.getToken(new String(credentials.get(UsersUtils.PREFERENCES_USER_KEY)),
new String(credentials.get(UsersUtils.PREFERENCES_PASS_KEY)));
return token;
}
};
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.subscribe(new DisposableSingleObserver<Token>() {
#Override
public void onSuccess(Token token) {
if (token == null) {
login();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onError(Throwable e) {
login();
}
});
}
public void login() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Thanks a lot for your help !

Android Webview signout issue

In my webview app when I run the app for the first time and log out from a user session, close the app and then when I open the app again instead of asking user credentials I find myself already logged in. I tried clearing cookies but then it always require sign in on every restart. I only want it to ask for sign in when the user logs out from the app.
Please Help!!
Here is a snippet of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.framelayout);
bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setMax(100);
webview = (WebView) findViewById(R.id.mywebview);
webview.clearCache(true);
webview.clearHistory();
WebSettings mWebSettings = webview.getSettings();
mWebSettings.setSaveFormData(false);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webview = (WebView) findViewById(R.id.mywebview);
webview.setWebViewClient(new HelpClient());
webview.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
bar.setProgress(newProgress);
setTitle("Loading....");
if (newProgress == 100){
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, newProgress);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.setVerticalScrollBarEnabled(false);
webview.loadUrl(WebAddress);
webview.loadUrl("javascript:window.location.reload(true)");
swipe.setRefreshing(false);
bar.setProgress(0);
}
private class HelpClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
try {
webview.stopLoading();
} catch (Exception e) {
}
if (webview.canGoBack()) {
webview.goBack();
}
webview.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(view, request, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if (webview.canGoBack()){
webview.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Run below code before loadUrl()
WebStorage webStorage = WebStorage.getInstance();
webStorage.deleteAllData();
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
I test it using Gmail account
CookieSynManager is now deprecated. This works for me :
WebStorage.getInstance().deleteAllData()
CookieManager.getInstance().removeAllCookies(null)

Remove any interstitial ads that appear after the user has exited the app

[Thanks for submitting your app to Google Play. I reviewed "app", and had to reject it because it violates our interfering with apps and third-party ads policy. If you submitted an update, the previous version of your app is still live on Google Play.
Here’s how you can submit your app for another review:
1)Remove any interstitial ads that appear after the user has exited the app, or after the user has pressed the back button to exit the app.
2)Read through the Interfering with Apps and Third-party Ads article for more details and examples.
3)Review your app to make sure it’s compliant with the Ads policy and all other policies listed in the Developer Program Policies. Remember that additional enforcement could occur if there are further policy issues with your apps.
4)Sign in to your Developer Console and submit your app.
If you’ve reviewed the ads policy and feel this rejection may have been in error, please reach out to our policy support team. One of my colleagues will get back to you within 2 business days.
I appreciate your support of Google Play!]1
please i want to know what is the problem and the sollution
Thank you.
enter code here/** The Admob ad. */
private InterstitialAd interstitialAd = null;
public AdView adView = null;
public static MainActivity app;
public void onCreate(Bundle savedInstanceState)
{
app = this;
super.onCreate(savedInstanceState);
// set view
mGLSurfaceView = new CCGLSurfaceView(this);
//Ads ----------------
// Create the adView
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//<!-- Ads Using Google Play Services SDK -->
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the adView to it
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
layout.addView(mGLSurfaceView);
layout.addView(adView);
setContentView(layout);
//New AdRequest
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//-----------------------------------------------------Interstitial Add
// Create an Interstitial ad.
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_INTERSTITIAL_UNIT_ID);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
interstitialAd.show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getApplicationContext(), "Interstitial Ads loading failed", Toast.LENGTH_SHORT).show();
}
});
// Load the interstitial ad.
//showInterstitialAds();
//----------------------
// set director
CCDirector director = CCDirector.sharedDirector();
director.attachInView(mGLSurfaceView);
director.setAnimationInterval(1/60);
// get display info
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
G.display_w = displayMetrics.widthPixels;
G.display_h = displayMetrics.heightPixels;
G.scale = Math.max(G.display_w/1280.0f, G.display_h/800.0f);
G.width = G.display_w / G.scale;
G.height = G.display_h / G.scale;
// get data
SharedPreferences sp = CCDirector.sharedDirector().getActivity().getSharedPreferences("GameInfo", 0);
G.music = sp.getBoolean("music", true);
G.sound = sp.getBoolean("sound", true);
// create sound
G.soundMenu = MediaPlayer.create(this, R.raw.menu);
G.soundMenu.setLooping(true);
G.soundGame = MediaPlayer.create(this, R.raw.game);
G.soundGame.setLooping(true);
G.soundCollide = MediaPlayer.create(this, R.raw.collide);
G.soundJump = MediaPlayer.create(this, R.raw.jump);
G.soundLongJump = MediaPlayer.create(this, R.raw.long_jump);
G.soundSpeedDown = MediaPlayer.create(this, R.raw.speed_down);
G.soundSpeedUp = MediaPlayer.create(this, R.raw.speed_up);
G.soundDirection = MediaPlayer.create(this, R.raw.direction_sign);
G.soundClick = MediaPlayer.create(this, R.raw.menu_click);
G.soundCollect = MediaPlayer.create(this, R.raw.collect);
G.bgSound = G.soundMenu;
// show menu
CCScene scene = CCScene.node();
scene.addChild(new MenuLayer(true));
director.runWithScene(scene);
}
#Override
public void onPause()
{
if (adView != null) {
adView.pause();
}
super.onPause();
G.bgSound.pause();
CCDirector.sharedDirector().onPause();
}
#Override
public void onResume()
{
super.onResume();
if (adView != null) {
adView.resume();
}
if( G.music ) G.bgSound.start();
CCDirector.sharedDirector().onResume();
}
#Override
public void onDestroy()
{
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
G.bgSound.pause();
CCDirector.sharedDirector().end();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
CCDirector.sharedDirector().onKeyDown(event);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void showInterstitialAds()
{
runOnUiThread(new Runnable() {
public void run() {
AdRequest interstitialAdRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialAdRequest);
}
});
}
}
GameLayer.java
Game over Method :
`public void gameOver()
{
_mask.runAction(CCFadeIn.action(0.6f));
_msg.setTexture(CCTextureCache.sharedTextureCache().addImage("game/failed_logo.png"));
_msg.runAction(CCSequence.actions(
CCEaseElasticOut.action(CCMoveTo.action(0.6f, G.displayCenter()), 0.5f),
CCDelayTime.action(0.5f),
CCEaseElasticIn.action(CCMoveTo.action(0.6f, CGPoint.ccp(-G.width*0.5f, G.height*0.5f)), 0.5f),
CCCallFunc.action(this, "restart")));
MainActivity.app.showInterstitialAds();
}`

Facebook webview called twice in Android app

I'm testing my app on a device where the Facebook application is not installed.
So when I'm logging with Facebook, a webview is opened.
The strange this is that when I've inserted my username and password, after pressing ok a webview is reopened and I've to insert the username and password again and I can login.
What could be ?
authButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
authButton.setVisibility(View.GONE);
logoutButton.setVisibility(View.VISIBLE);
// start Facebook Login
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
SharedPreferences.Editor edit = pref.edit();
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
accesstoken = session.getAccessToken();
edit.putString("fbtoken", accesstoken);
if (session.getExpirationDate()!= null)
edit.putLong("com.facebook.sdk.AccessTokenExpires", session.getExpirationDate().getTime());
Log.d("FACEBOOK", "LOGGED IN");
}
});
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
Login.this, PERMISSIONS);
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
// make request to the /me API
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d("FACEBOOK", "onCompleted");
Log.d("",""+user);
try {
name=user.getName();
email=user.getProperty("email").toString();
location=(user.getLocation().getProperty("name").toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("ID", user.getId());
}
}).executeAsync();
}
}
});
}
});
I've had the same problem on iOS so this problem could be linked.
I solved it by removing the delegate after I received the first response.
So it may be applicable in your exemple like this:
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
if (logoutButton.getVisibility() == View.VISIBLE) {
// Its visible so we end the callback
return;
}
SharedPreferences.Editor edit = pref.edit();
My guess is that you're saving the access token into the shared pref,
and it needs some time to be saved on disk if you don't force it.
You should add
edit.putLong("com.facebook.sdk.AccessTokenExpires", ...);
edit.commit(); // <- this line
so you are sure that for the next call it will be available