Tuesday, August 25, 2015

How to Enable or Disable a button in runtime in Android

While I was working with an Android application for a customer, there was a use case to disable a button in the run time. And need to enable it after some action. We can do it very easily in Android.


I have a “About” button in the screen. And I need to enable and disable the button based on the network status. In xml, we have the button as below:

<Button
        android:id="@+id/about_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="64dp"
        android:text="@string/about_label" />     

You need to reference it in the activity using findViewById in onCreate() method:

View aboutButton = findViewById(R.id.about_button);

You can enable or disable by setting  setEnabled() to true or false.

To enable: setEnabled(true);
And to disable: setEnabled(false);

aboutButton.setEnabled(false);

Now, I am going to enable it if the connectivity is available. I have added a class- NetworkUtil to check the network status. You can download it from here. (NetworkUtil) and use it in your activity to check the status. You need to create an object for this class and use the method: getConnectivityStatus. Here is the code to do so:

NetworkUtil net =new NetworkUtil();
      int status = net.getConnectivityStatus(getApplicationContext());
        if(status!=0){
            aboutButton.setEnabled(true);
        }
        else{
            aboutButton.setEnabled(flase);
     
          }                 

That’s it. Happy Coding..



Saturday, August 22, 2015

How to know if AdMob ad has been loaded in your Android Application

In my last blog we have discussed about adding an ad from Admob network. This is in continuation with that.


In the applications we may need to take some action if the ad is loaded and some other action if the ad is not loaded. In such cases it’s very much important to know if the Admob ad is loaded to our application or not. We can achieve using the setAdListener interface of AdView. Below is the code which can be used to achieve this:

ad.setAdListener(new AdListener() {                 
              @Override
              public void onAdLoaded() {
                    Log.d(TAG, "Ad Received");
                    //Code implementation if the ad is loaded
                       ………
                      ………
                  }
               @Override
               public void onAdFailedToLoad(int errorcode) {
                      Log.d(TAG, "Ad Not Loaded Received");
                 //Code implementation if the ad is NOT loaded
                   ………
                 ………
               }
             });

onAdLoaded is the method which is used to check if the ad is loaded. And
onAdFailedToLoad is the method used to check if the ad is not loaded. Based on these implementation you can implement your respective action code.

Also you need to fetch the ads only if you have the network connectivity otherwise it just keeps trying to fetch the ad which may slow your application. We can check the network status before we fetch and load the ads. To check the network status you can use ConnectivityManager class. 

private static final String DEBUG_TAG = "NetworkStatusExample";

...      

ConnectivityManager connMgr = (ConnectivityManager) 

        getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 

boolean isWifiConn = networkInfo.isConnected();

networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

boolean isMobileConn = networkInfo.isConnected();

Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);

Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);

For this I have added a class- NetworkUtil to check the network status. You can download it from here. (NetworkUtil) and use it in your activity to check the status. You need to create an object for this class and use the method: getConnectivityStatus. Here is the code to do so:

NetworkUtil net =new NetworkUtil();
       int status = net.getConnectivityStatus(getApplicationContext());
        if(status!=0){
            //Code if the network connection is there      
        }
        else{
            //Code if the network connection is NOT there     
          }

The final code looks like this:

      NetworkUtil net =new NetworkUtil();
        AdView ad=(AdView)findViewById(R.id.adView);        
        int status = net.getConnectivityStatus(getApplicationContext());
        if(status!=0){
            ad.loadAd(new AdRequest.Builder().build());
           ad.setAdListener(new AdListener() {
                 @Override
                  public void onAdLoaded() {
                           Log.d(TAG, "Ad Received");
                           //code when the ad loaded
                  }
                 @Override
                  public void onAdFailedToLoad(int errorcode) {
                           Log.d(TAG, "Ad Not Loaded Received");
                           //code if the ad loading is failed
                  }
           });            
        }
       else{
                  //Code if the network connection is NOT there                
        }

That’s it. Happy Coding..

Friday, August 21, 2015

Integrating Google AdMob Ads in Android Application

I was wondering how to integrate Advertises from google in my Android applications. AdMob is the best mobile advertising site which you can integrate with your Android Application very easily.
In this blog, you learn how to show AndMob Advertises in your Android Application.  This write up is divided into below three parts: 

1.     Getting Ad Unit Id from Admob Site
2.     Installing Google Play Services in Android SDK
3.     Integrating AdSense code to Android App.

1)     Getting Ad Unit Id from Admob Site :

1.     Go to AdMob Site

2.     Create New Account (if you are already an admob user, then log in)

3.     Select "Monetize new app" option.


4.   Search your android application for which you want to integrate the Admob. You can search it in Google Play or you can add the details about the application.



       5. After filling all information, you get the instructions to set up admob unit id.


6. Now, your app is added to the admob site. You can check this in all apps list in Monetize tab of        this site. You can select this app and create the ad banner and get the ad unit id which looks as:
ca-app-pub-50xxxx69xxxxxxxx/34xxxxxxxx

7.  You need to use this Ad Unit Id in our project later.


2)     Installing Google Play Services in Android SDK


1.     Open the Eclipse and Go to Windows-&gt;SDK Manager :



2.  In the packages select Extras-&gt;Check Google Play Services and install it as shown below: 


3.    Import the Google play Services to you Workspace.

4.   Now Go to your project where you want to integrate this admob, and add this Google play services library to this project: 




3)     Integrating AdSense code to Android App:

     1.  Open your android XML file and add the following line in layout:

xmlns:ads=http://schemas.android.com/apk/res-auto      
  
2.     Add AdView in Layout:

<com.google.android.gms.ads.AdView
 android:id="@+id/adView"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 ads:adSize="BANNER"
 ads:adUnitId="YOUR_AD_UNIT_ID"

/>

3.    Now open your Java file and initialize AdView Object in your Activity:
AdView ad=(AdView)findViewById(R.id.adView);
     4.   Load Ad from Google:
ad.loadAd(new AdRequest.Builder().build());
5.  Now modify the AndroidManifest.xml:

      a.      Add Permissions: 

<!-- Used to request banner ads. -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Used to avoid sending an ad request if there is no connectivity. -->

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

     b.     Need to add metadata of Google play Services: 

<meta-data
 android:name="com.google.android.gms.version"

 android:value="@integer/google_play_services_version" />

           
     c.    Need to add the below activity to show the ad overlays:

<activity
 android:name="com.google.android.gms.ads.AdActivity"

  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

  d.      Final AndroidManifest.xml looks as below:
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.marutsoft.sudoku"
      android:versionCode="3"
      android:versionName="1.3">
    <uses-sdk android:minSdkVersion="7"
        android:targetSdkVersion="19"/>
    <!-- Used to request banner ads. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Used to avoid sending an ad request if there is no connectivity. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
        <meta-data
 android:name="com.google.android.gms.version"
 android:value="@integer/google_play_services_version" />

         <activity android:name="com.marutsoft.sudoku.Splash"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
          
        <!-- Activity required to show ad overlays. -->
<activity
 android:name="com.google.android.gms.ads.AdActivity"
 android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
            
    </application>

</manifest>
   
Now run your application and check that google adverise is shown in the activity where you have added it. Please note you need to have the internet connectivity.

Also you can add the code to check the availability of the connectivity and then load the advertise. We will add that part in my next blog

That’s it. Happy Coding..