I have implemented following code for interstitial ads .Problem I am facing is that interstitial ad is shown only on first URL click. I want to adjust ads on every URL click or every 5th URL click in WebView app .Help in this regard will highly be appreciated. Following is the code i want to be modified .
private WebView webview;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", 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");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
You need to load Ad after each show. Create a static counter variable to load it on everyth nth click.
static int instanceCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadInterstitial();
}
private void LoadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", 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");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null && isDisplayAdvert()) {
mInterstitialAd.show(MainActivity.this);
LoadInterstitial();
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
private bool isDisplayAdvert(){
instanceCounter++;
if(instanceCounter==5){
instanceCounter = 0;
return true;
}
return false;
}
Thanks sir Amod Gokhale . I tried the following code and it is working too .
Would you recommend me about the better one between both codes .
private class WebViewClientDemo extends WebViewClient {
int n = 1;
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
if( n%6 == 0 )
{
mInterstitialAd.show(MainActivity.this);
} n++;
}
LoadInterstitial();
return super.shouldOverrideUrlLoading(view, url);
}
Related
I want to display my Firebase notification message in textviews in background mode, but it's only working and displaying in foreground mode.
I have already used broadcastReceiver. It is working, but only in the foreground. How can I make it work in background mode?
This is my Firebase Messaging Service class:
public class ProfileActivity extends AppCompatActivity {
TextView notificationTitle, notificationMessage;
public static final String NODE_USERS = "users";
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver(mHandler,new IntentFilter("com.example.linguanotification_FCM-MESSAGE"));
setContentView(R.layout.activity_profile);
notificationTitle=findViewById(R.id.title_notification);
notificationMessage=findViewById(R.id.notification_message);
mAuth = FirebaseAuth.getInstance();
FirebaseMessaging.getInstance().subscribeToTopic("updates");
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
saveToken(token);
} else {
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
private void saveToken(String token) {
String email = mAuth.getCurrentUser().getEmail();
User user = new User(email, token);
DatabaseReference dbUsers = FirebaseDatabase.getInstance().getReference(NODE_USERS);
dbUsers.child(mAuth.getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Token Saved", Toast.LENGTH_LONG).show();
}
}
});
}
private BroadcastReceiver mHandler = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("title");
String message=intent.getStringExtra("message");
notificationTitle.setText(title);
notificationMessage.setText(message);
}
};
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(), title, body);
}
if (remoteMessage.getData().size()>0)
{
String title = remoteMessage.getData().get("title");
String message= remoteMessage.getData().get("message");
Intent intent = new Intent("com.example.linguanotification_FCM-MESSAGE");
intent.putExtra("title",title);
intent.putExtra("message",message);
LocalBroadcastManager localBroadcastManager=LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
}
public class NotificationHelper {
public static void displayNotification(Context context, String title, String body) {
Intent intent = new Intent(context, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.dd)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(context);
mNotificationMgr.notify(1, mBuilder.build());
}
}
public class MainActivity extends AppCompatActivity {
//1. Notification Channel
//2. Notification Builder
//3. Notification Manager
public static final String CHANNEL_ID = "12";
public static final String CHANNEL_NAME = "23";
public static final String CHANNEL_DESC = "34";
private EditText editTextEmail, editTextPassword;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.INVISIBLE);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
findViewById(R.id.buttonSignUp).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createUser();
}
});
}
private void createUser() {
final String email = editTextEmail.getText().toString().trim();
final String password = editTextEmail.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email required");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Password should be atleast 6 char long");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
startProfileActivity();
}else{
if(task.getException() instanceof FirebaseAuthUserCollisionException){
userLogin(email, password);
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
private void userLogin(String email, String password){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
startProfileActivity();
}else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
//here we are checking if the user is not null then the user already logged in
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null)
{
startProfileActivity();
}
}
private void startProfileActivity() {
Intent intent = new Intent(this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
If I have created a deep link using the branch.io that opens a specific screen in my app. If this link is also available in my app and a user clicks on it, will it open my screen? or it will do nothing as the link I am trying to open from the app is pointing to the same app?
When you click on a Branch link within a webView in your App, you will have to handle the routing to the specific Activity, after reading the Branch link parameters.
Here is a sample Activity which contains a webView and and shows a couple of Branch links. When you click on a link in the webView it reopens the webview and displays the link parameters in a Toast message if a Branch link is clicked
public class MainActivity extends AppCompatActivity {
private WebView webView_;
private Button button_;
private String TAG = "WebViewController";
private Context context_;
private static final String URL_TO_LOAD = "https://evangelosg.github.io/index.html";
private static final String BRANCH_LINK_TO_LOAD = "https://ere6.app.link/b6sS0gsCfG";
#Override
protected void onNewIntent(Intent intent) {
Log.d("WebView", "onNewIntent");
setIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
Branch branch = Branch.getInstance();
branch.initSession(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
Log.d(TAG, referringParams.toString());
Toast.makeText(context_, referringParams.toString(), Toast.LENGTH_LONG).show();
if (referringParams.has(BundleExtraKeys.CLICKED_BRANCH_LINK)) {
try {
boolean clickedBranchLink = referringParams.getBoolean(BundleExtraKeys.CLICKED_BRANCH_LINK);
if (clickedBranchLink) {
//do stuff!
}
} catch (JSONException e) {
Log.d("BranchTrends", e.getMessage());
}
}
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context_ = this;
setContentView(R.layout.activity_main);
webView_ = (WebView) findViewById(R.id.webView);
webView_.setWebViewClient(new BranchWebViewController("app.link", MainActivity.class));
webView_.loadUrl(URL_TO_LOAD);
button_ = (Button) findViewById(R.id.button);
button_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.putExtra("branch", BRANCH_LINK_TO_LOAD);
customTabsIntent.intent.putExtra("branch_force_new_session", true);
finish();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(BRANCH_LINK_TO_LOAD));
}
});
}
public class BranchWebViewController extends WebViewClient {
private String myDomain_;
private Class activityToLaunch_;
BranchWebViewController(#NonNull String myDomain, Class activityToLaunch) {
myDomain_ = myDomain;
activityToLaunch_ = activityToLaunch;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(myDomain_)) {
Intent i = new Intent(view.getContext(), activityToLaunch_);
i.putExtra("branch", url);
i.putExtra("branch_force_new_session", true);
finish();
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
}
Once you read the link parameters you can route to the appropriate Activity based on the link parameters.
I have a list of webview to show different pdf's, I need to show it in a horizontal RecyclerView, but the problem is that when I scroll it horizontally then the coming webview just goes on top of the current one and the current one instead of shifting to the left hand side, it remains at its position. It looks a little weird.
This is my RecyclerViewAdapter
public class HorizontalManual extends RecyclerView
.Adapter {
Context context;
private ArrayList<String> list;
public class DataObjectHolder extends RecyclerView.ViewHolder {
ImageView imgUploaded;ProgressBar loader; WebView webViewManual;
public DataObjectHolder(View itemView) {
super(itemView);
webViewManual = (WebView) itemView.findViewById(R.id.pdf_manual_webView);
}
}
public HorizontalManual(Context context, ArrayList<String> list) {
this.context = context;
this.list = list;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = null;
try {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.horz_pdf, parent, false);
if (view.getLayoutParams ().width == RecyclerView.LayoutParams.MATCH_PARENT)
view.getLayoutParams ().width = parent.getWidth ();
} catch (Exception e) {
e.printStackTrace();
}
return new DataObjectHolder(view);
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
String url = "http://docs.google.com/gview?embedded=true&url=" + list.get(position);
Log.e("pdf",url);
WebSettings websettings = holder.webViewManual.getSettings();
websettings.setJavaScriptEnabled(true);
holder.webViewManual.loadUrl(url);
holder.webViewManual.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
holder.webViewManual.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('ndfHFb-c4YZDc-GSQQnc-LgbsSe ndfHFb-c4YZDc-to915-LgbsSe VIpgJd-TzA9Ye-eEGnhe ndfHFb-c4YZDc-LgbsSe')[0].style.display='none'; })()");
}
});
holder.webViewManual.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
holder.webViewManual.setHorizontalScrollBarEnabled(false);
}
#Override
public int getItemCount() {
return list.size();
}
}
I'm setting the HorizontalList in my Fragment like this:
mRecyclerViewManual.setHasFixedSize(true);
rLayoutManagerManual = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); mRecyclerViewManual.setLayoutManager(rLayoutManagerManual);
//Setting adapter
HorizontalManual setUploadsListAdapterManual = new HorizontalManual(context, list); mRecyclerViewManual.setAdapter(setUploadsListAdapterManual);
Load you google doc url using iframe tag as shown below.
String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://docs.google.com/gview?embedded=true&url=http://Dealerapp.ebunch.ca/upload/wl/manuals/7.pdf\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
holder.webView.loadData(frameVideo, "text/html", "utf-8");
I'm using RoboVM bindings for my iOS application to display AdMob interstitials. When I close the interstitial ad, I lose all touch controls. Is there a way to detect the ad being closed so I can put the touch back to the game? Or is there a better way to implement interstitials? Here's my code below:
public class IOSLauncher extends IOSApplication.Delegate implements IActivityRequestHandler{
private static final Logger log = new Logger(IOSLauncher.class.getName(), Application.LOG_DEBUG);
private IOSApplication iosApplication;
//interstitial
private static final String INTERSTITIAL_AD = "MY_AD_ID";
private GADInterstitial interstitial;
private UIWindow window;
private UIViewController rootViewController;
#Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = true;
config.orientationPortrait = false;
iosApplication = new IOSApplication(new PaperPig(this), config);
return iosApplication;
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
#Override
public void initializeAds() {
intializeInterstitial();
}
public void intializeInterstitial () {
rootViewController = new UIViewController();
interstitial = new GADInterstitial();
interstitial.setAdUnitID(INTERSTITIAL_AD);
interstitial.setDelegate(new GADInterstitialDelegateAdapter() {
#Override
public void didReceiveAd (GADInterstitial ad) {
System.out.println("Did receive ad.");
}
#Override
public void didFailToReceiveAd (GADInterstitial ad, GADRequestError error) {
System.out.println(error.description());
System.out.println(error.getErrorCode());
}
});
window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(rootViewController);
window.addSubview(rootViewController.getView());
interstitial.loadRequest(GADRequest.create());
}
#Override
public void showOrLoadInterstital() {
if (interstitial.isReady()) {
if (rootViewController == null) {
rootViewController = new UIViewController();
}
if (window == null) {
window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(rootViewController);
}
window.makeKeyAndVisible();
interstitial.present(rootViewController);
}
//Return touch back to Game
//UIApplication.getSharedApplication().getKeyWindow().setRootViewController(rootViewController);
}
}
You need to call:
window.setHidden(true);
Change your creation of GADInterstitialDelegateAdapter() to the following
interstitial.setDelegate(new GADInterstitialDelegateAdapter() {
#Override
public void didReceiveAd (GADInterstitial ad) {
System.out.println("Did receive ad.");
}
#Override
public void didDismissScreen(GADInterstitial ad) {
window.setHidden(true);
}
#Override
public void didFailToReceiveAd (GADInterstitial ad, GADRequestError error) {
System.out.println(error.description());
System.out.println(error.getErrorCode());
}
});
I'm trying to show interstitial ads in some urls of my webview app, including onPagefinished and url.contains, but it doesn´t work. Here's my code:
#SuppressLint("SetJavaScriptEnabled") public class Juego extends ActionBarActivity {
/** ID intersticial */
private InterstitialAd interstitialAd;
private static final String AD_UNIT_ID = "ca-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
//Página web enlazada:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://xxxxxxxxxxxxxxxxx.php");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.setVerticalScrollBarEnabled(false);
myWebView.setHorizontalScrollBarEnabled(false);
//Barra de progreso
final Activity activity = this;
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressDialog.setTitle("Cargando");
progressDialog.setMessage("Por favor espera");
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1);
progressDialog.incrementProgressBy(progress);
if(progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
public void onPageFinished (WebView view, String url) {
// Anuncios intersticiales: Create the interstitial.
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitialAd.loadAd(adRequest);
if (url.contains("game")) {
interstitialAd.show();
}
}
}
Any help?
use this
public void onPageFinished (WebView view, String url) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-5236990339136194/xxxxxxxxxx");
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener(){
public void onAdLoaded(){
displayInterstitial();
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
} );
}
and don't forget add this on your onCreate blog
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);