Showing posts with label Android Tutorials. Show all posts
Showing posts with label Android Tutorials. Show all posts

Friday, 31 January 2020

How to implement Facebook audience network banner ad in android app using Android Studio

Its very simple to implement Facebook audience network banner ad in android app using Android Studio. We will complete it in 4 Steps.

1. Creating Android Studio Project and adding Facebook Audience network dependency in the project
2. Adding layout for banner add in layout xml file
3. Initializing Facebook Audience network SDK and finally showing banner ad
4. Adding internet permission in Manifest file

1. Creating Android Studio Project and adding Facebook Audience network dependency in the project

Create an android studio project for creating an android app and wait for project build completion.
Now open build.gradle (App level) file and add the following dependency between dependencies section.
(At the time of writing this article this is the latest version)
implementation 'com.facebook.android:audience-network-sdk:5.6.1'

2. Adding layout for banner add in layout xml file

To show banner ad in our application, it needs any container which can hold the banner ad. So here we are using LinearLayout as a container. and we are giving its id as bannerAdContainerLinearLayout.

<LinearLayout  
   android:layout_width="match_parent" 
   android:orientation="vertical"    
   android:layout_alignParentBottom="true"    
   android:id="@+id/bannerAdContainerLinearLayout" 
   android:layout_height="wrap_content">
</LinearLayout>

3. Initializing Facebook Audience network SDK and finally showing banner ad

To show ads using Facebook Audience network in our application it is necessary that it should be initialized correctly. To initialize the Facebook Audience network SDK write the below code into your MainActivity.java OnCreate method.

AudienceNetworkAds.initialize(this);

//below statements are optional and will be used when you are testing your app and its not in release
//for testing only
AdSettings.setTestAdType(AdSettings.TestAdType.IMG_16_9_APP_INSTALL);
//for testing only
AdSettings.getTestAdType();
//for testing only
dSettings.addTestDevice("Device hash id");
Now we initialized the SDK, its time to load banner ad and show the ad
// creating adView object with our placement ID
AdView adView = new AdView(this, "IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID", AdSize.BANNER_HEIGHT_50);
// finding linear layout container for banner which we have defined in our layout file
LinearLayout bannerAdContainer = findViewById(R.id.bannerAdContainerLinearLayout);
//adding adView to container
bannerAdContainer.addView(adView);
// loading our ad into adview and showing it to the user
adView.loadAd();

4. Adding internet permission in Manifest file

We will be able to show any ad to the user if our app has internet access permission.
So we have it add this permission into out AndroidManifest.xml file.
Add this line between <manifest> starting and closing tag
<uses-permission android:name="android.permission.INTERNET"/>




Now launch the application and we will see a test banner ad from facebook


















Saturday, 15 December 2018

Auto check for update function for android app | android studio

If you are having an app on Google Play Store and you want that whenever you update the app on playstore and when the user opens the older version of app he/she will get a dialog that there is an Update available .
Each time the user will open the app he/she will get the same dialog until he/she updates the app.

Advantages:

This will inform the user as a notice that there is an update.

Users will have the latest version of app.
Automatically checks for update in the background.
There is also an option for mannual check and automatic check.




How to use:

Step-I
I have already create a class(AppUpdateChecker.java) to achieve this feature that will handle it automatically.

AppUpdateChecker.java
 
 package com.programmingdesire;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.content.DialogInterface;  
 import android.content.Intent;  
 import android.content.pm.PackageInfo;  
 import android.content.pm.PackageManager;  
 import android.net.Uri;  
 import android.os.AsyncTask;  
 import android.support.v7.app.AlertDialog;  
 import android.widget.Toast;  
 import org.jsoup.Jsoup;  
 public class AppUpdateChecker {  
   private Activity activity;  
   public AppUpdateChecker(Activity activity) {  
     this.activity = activity;  
   }  
   //current version of app installed in the device  
   private String getCurrentVersion(){  
     PackageManager pm = activity.getPackageManager();  
     PackageInfo pInfo = null;  
     try {  
       pInfo = pm.getPackageInfo(activity.getPackageName(),0);  
     } catch (PackageManager.NameNotFoundException e1) {  
       e1.printStackTrace();  
     }  
     return pInfo.versionName;  
   }  
   private class GetLatestVersion extends AsyncTask<String, String, String> {  
     private String latestVersion;  
     private ProgressDialog progressDialog;  
     private boolean manualCheck;  
     GetLatestVersion(boolean manualCheck) {  
       this.manualCheck = manualCheck;  
     }  
     @Override  
     protected void onPostExecute(String s) {  
       super.onPostExecute(s);  
       if (manualCheck)  
       {  
         if (progressDialog!=null)  
         {  
           if (progressDialog.isShowing())  
           {  
             progressDialog.dismiss();  
           }  
         }  
       }  
       String currentVersion = getCurrentVersion();  
       //If the versions are not the same  
       if(!currentVersion.equals(latestVersion)&&latestVersion!=null){  
         final AlertDialog.Builder builder = new AlertDialog.Builder(activity);  
         builder.setTitle("An Update is Available");  
         builder.setMessage("Its better to update now");  
         builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {  
           @Override  
           public void onClick(DialogInterface dialog, int which) {  
             //Click button action  
             activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+activity.getPackageName())));  
             dialog.dismiss();  
           }  
         });  
         builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {  
           @Override  
           public void onClick(DialogInterface dialog, int which) {  
             //Cancel button action  
           }  
         });  
         builder.setCancelable(false);  
         builder.show();  
       }else {  
         if (manualCheck) {  
           Toast.makeText(activity, "No Update Available", Toast.LENGTH_SHORT).show();  
         }  
       }  
     }  
     @Override  
     protected void onPreExecute() {  
       super.onPreExecute();  
       if (manualCheck) {  
         progressDialog=new ProgressDialog(activity);  
         progressDialog.setMessage("Checking For Update.....");  
         progressDialog.setCancelable(false);  
         progressDialog.show();  
       }  
     }  
     @Override  
     protected String doInBackground(String... params) {  
       try {  
         //It retrieves the latest version by scraping the content of current version from play store at runtime  
         latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + activity.getPackageName() + "&hl=it")  
             .timeout(30000)  
             .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")  
             .referrer("http://www.google.com")  
             .get()  
             .select(".hAyfc .htlgb")  
             .get(7)  
             .ownText();  
         return latestVersion;  
       } catch (Exception e) {  
         return latestVersion;  
       }  
     }  
   }  
   public void checkForUpdate(boolean manualCheck)  
   {  
     new GetLatestVersion(manualCheck).execute();  
   }  
 }  

Step-II
Add a library to your build.gradle(App level) file.

   implementation 'org.jsoup:jsoup:1.10.2'  

Step-III
The last step is to copy that class and then write two lines of code.


 AppUpdateChecker appUpdateChecker=new AppUpdateChecker(this);  //pass the activity in constructure
 appUpdateChecker.checkForUpdate(false); //mannual check false here

Lets understand what is manual check

If manual check is true then
Manual check will be on a button click this will show the dialog as "Checking for update"



If manual  check is false then
Checking for update will be performed in the background and finally a dialog will be visible if there is any update.


If user will click on update it will open your app in playstore to update your app.

Thats all.

Thanks for visiting, I will come with new code snippet.
Happy Coding.......





Tuesday, 6 November 2018

Picasso Android Tutorial – Android Picasso Image Loader Library

Hello programmers, today we will be learning about picasso library for image downloading developed by sqaure.
  • Picasso one of the most popular library for image downloading.
  • It makes our wok very simple so its powerful library for image downloading.
  • It uses caching technique.
  • I have already published a post on Glide(similar to picasso) Image Downloading library for android.


Why Picasso library?

Its obvious that you will think why we should use picasso library.
If we use the traditional method of downloading the image from a url then we need to manage a lots of thing.
 And of course lines of code and development time will also increase.
 But if we will use a 3rd party library like picasso then we will achieve our goal in few lines of code.  So if we will not use a 3rd party library then  we would need
  1. Very large amount of code to be written
  2. We have to write another logic to implement caching.
  3. Caching is very important to make the application faster.
  4. We also have to deal with memory while writing the code.
  5. If any error occurs we need to handle that also.
  6. we will not focusing more on the application feature that is going to be developed. 
So, picasso will handle these all by default and overcome these all problems.

Adding Picasso Library to our Android Project

Adding picasso android library to your project is very easy.
Add the following line in the dependency block of your build.gradle file(app /module level).
I am assuming that you are using Android Studio.
After adding it just sync your project.

Loading Image from URL by Using Picasso Android Library

Loading image from URL by using Picasso Android Library is very simple and easy. The first thing we would need is an ImageView. 

Code for Loading Image with Picasso

It is very simple. We have to use the Picasso class.

 Picasso.get()  
 .load(IMAGE_URL)  
 .into(imageView);  


Placeholder and Error Handling

  • Because we are loading the image from internet.
  • the process would take some time depending on the internet speed. 
  • So it would be a good idea to display a image from the device while the image from URL is getting loaded.
  • One more situation could be when the image is not downloaded from the URL (when the URL given is wrong). 
  • In this case we should display an error image.
  • Both these things can be done very easily by using picasso.
  • See the following code snippet.

  Picasso.get()
   .load("YOUR IMAGE URL HERE")  
   .placeholder(Your Drawable Resource) // optional the image to display while the url image is downloading  
   .error(Your Drawable Resource) //this is also optional if some error has occurred in downloading the image                                  //this image would be displayed  
   .into(imageView);  

Re-sizing and Rotating

We can also resize and rotate the image very easily.


 Picasso.with(this)  
    .load("YOUR IMAGE URL HERE")      
    .placeholder(DRAWABLE RESOURCE)  // optional      
    .error(DRAWABLE RESOURCE)   // optional      
    .resize(width, height)            // optional      
    .rotate(degree)               // optional      
    .into(imageView);  


Using Picasso Android Library in Our Project

Now lets try the above codes in our Android Studio Project. So I will be creating a new Android Project.

  • Open Android Studio and create a new project.
  • I have created PicassoExample. 
  • First we have to add the Picasso Library. 
  • So open your build.gradle(app level) and add the following line inside dependency block and sync your project.
  • As we will load the image from a URL so we will also need internet permission. 
  • So open AndroidManifest.xml and add internet permission.
 <?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:orientation="vertical"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity">  
   <ImageView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_centerInParent="true"  
     android:src="@mipmap/ic_launcher_round"  
     android:id="@+id/imageView"  
     />  
   <Button  
     android:layout_width="match_parent"  
     android:id="@+id/btn"  
     android:layout_below="@+id/imageView"  
     android:layout_centerHorizontal="true"  
     android:text="show image"  
     android:layout_margin="10dp"  
     android:layout_height="wrap_content" />  
 </RelativeLayout>  


  • Now come inside MainActivity.java and define your ImageView and a button.

MainActivity.java 

 package protector.video.com.picasoexample;  
 import android.os.Bundle;  
 import android.support.v7.app.AppCompatActivity;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.ImageView;  
 import com.squareup.picasso.Picasso;  
 public class MainActivity extends AppCompatActivity {  
   private ImageView imageView;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     Button btn=findViewById(R.id.btn);  
     imageView=findViewById(R.id.imageView);  
     //setting click listener to the button
     btn.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         Picasso.get()  
             .load("https://avatars0.githubusercontent.com/u/1?v=4")  
             .placeholder(R.drawable.ic_image_black_24dp) // optional the image to display while the url image is downloading  
             .error(R.drawable.ic_error_black_24dp) //this is also optional if some error has occurred in downloading the image                 //this image would be displayed  
             .into(imageView);  
       }  
     });  
   }  
 }  
  • We need two images one for placeholder and one for error. I will be using the following images. Just save these and paste inside the drawable folder of your project.
  • Now we need a URL to an ImageFile. I have this URL https://avatars0.githubusercontent.com/u/1?v=4


Finally run your application. 
Picasso Android 
Happy coding......
Thank You

Monday, 5 November 2018

Glide - Image Download library for android

What is Glide?

  • Glide is an open source media management framework for Android.
  • Control media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface
  • Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs.
  • Glide includes a flexible API that allows developers to plug in to almost any network stack 
  • Glide’s primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.

Glide Unique Features

  1. Animated GIF decoding : you can load GIF animation into ImageView.
  2. Supports Thumbnail
  3. Supports OkHttp and Volley library & retrofilt library
  4. Placeholder can be added before loading the original image.
  5. Any custom image can be shown if error occurs while loading the original image.

Alternatives of Glide 

  •  Picasso  

Why Image loader library? 

  • To show an image into ImageView from a url we need to download that image
  • downloading the complete image from remote location, handle network errors if occurs while downloading. 
  • Implement image caching.
To download an image one should do a lot of things.
This will increase the lines of code and of course development time.
So its better to use the library to reduce our work and focus more on the development idea.

Steps to use Glide?

step 1.

 Add dependency for Glide into app/build.gradle.
dependencies {

implementation 'com.github.bumptech.glide:glide:4.8.0
} 

Step 2.

 Add INTERNET permission in manifest file 

 <uses-permission android:name="android.permission.INTERNET" /> 

Step 3

 Add ImageView in you layout

Declare an ImageView in your layout to display image from remote server in it
 <ImageView  
   android:layout_width="wrap_content"  
   android:layout_height="wrap_content"  
   android:id="@+id/imageView">  
 </ImageView>

Step 4 

 Add ImageView in you layout


 Glide.with(this)  
     .load("IMAGE URL HERE")  
     .placeholder(R.drawable.placeholder)  
     .error(R.drawable.imagenotfound)  
     .into(imageView);



MainActivity.java

 public class MainActivity extends AppCompatActivity {  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     final String url="https://avatars0.githubusercontent.com/u/1?v=4";  
     //Glide  
     Button btn=findViewById(R.id.btn);  
     final ImageView imageView=findViewById(R.id.img);  
     btn.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         Glide.with(MainActivity.this).load(url).into(imageView);  
       }  
     });  
   }  
 }  

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout 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:orientation="vertical"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity">  
   <ImageView  
     android:layout_width="wrap_content"  
     android:id="@+id/img"  
     android:src="@mipmap/ic_launcher"  
     android:layout_height="wrap_content" />  
   <Button  
     android:layout_width="wrap_content"  
     android:text="Download image and show"  
     android:id="@+id/btn"  
     android:layout_height="wrap_content" />  
 </LinearLayout>  

How to implement Facebook audience network banner ad in android app using Android Studio

Its very simple to implement Facebook audience network banner ad in android app using Android Studio. We will complete it in 4 Steps. 1. ...