Sunday, March 2, 2014

[Android Useful Examples] Android Wi-Fi Tutorial

Android allows applications to access to view the access the state of the wirless connections at very low level. Application can access almost all the information of a wifi connection.
The information that an application can access includes connected network's link speed,IP address, negotiation state, other networks information. Applications can also scan, add, save, terminate and initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this class by calling getSystemService method. Its syntax is given below:
WifiManager mainWifiObj;
mainWifiObj =(WifiManager) getSystemService(Context.WIFI_SERVICE);
undefined
In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered using registerReceiver method with argument of your reciever class object. Its sytanx is given below:
classWifiScanReceiverextendsBroadcastReceiver{
   publicvoid onReceive(Context c,Intent intent){
   }}WifiScanReceiver wifiReciever =newWifiScanReceiver();
registerReceiver(wifiReciever,newIntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));  
The wifi scan can be start by calling the startScan method of the WifiManager class. This method returns a list of ScanResult objects. You can access any object by calling the get method of list. Its syntax is given below:
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();String data = wifiScanList.get(0).toString();
Apart from just Scanning , you can have more control over your WIFI by using the methods defined in WifiManager class. They are listed as follows:
Sr.NoMethod & Description
1addNetwork(WifiConfiguration config)
This method add a new network description to the set of configured networks.
2createWifiLock(String tag)
This method creates a new WifiLock.
3disconnect()
This method disassociate from the currently active access point.
4enableNetwork(int netId, boolean disableOthers)
This method allow a previously configured network to be associated with.
5getWifiState()
This method gets the Wi-Fi enabled state
6isWifiEnabled()
This method return whether Wi-Fi is enabled or disabled.
7setWifiEnabled(boolean enabled)
This method enable or disable Wi-Fi.
8updateNetwork(WifiConfiguration config)
This method update the network description of an existing configured network.

Example

Here is an example demonstrating the use of WIFI. It creates a basic application that scans a list of wirless networks and populate them in a list view.
To experiment with this example , you need to run this on an actual device on which wifi is turned on.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as WIFI under a package com.example.wifi. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add WebView code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the AndroidManifest.xml to add the necessary permissions
5Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modifed main activity file src/com.example.wifi/MainActivity.java.
package com.example.wifi;

import java.util.List;

import android.annotation.SuppressLint;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.net.wifi.ScanResult;import android.net.wifi.WifiManager;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;

publicclassMainActivityextendsActivity{

   WifiManager mainWifiObj;
   WifiScanReceiver wifiReciever;
   ListView list;
   String wifis[];
   publicvoid onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      list =(ListView)findViewById(R.id.listView1);
      mainWifiObj =(WifiManager) getSystemService(Context.WIFI_SERVICE);
      wifiReciever =newWifiScanReceiver();
      mainWifiObj.startScan();
   }


   protectedvoid onPause(){
      unregisterReceiver(wifiReciever);
      super.onPause();
   }

   protectedvoid onResume(){
      registerReceiver(wifiReciever,newIntentFilter(
      WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
      super.onResume();
   }

   classWifiScanReceiverextendsBroadcastReceiver{
      @SuppressLint("UseValueOf")
      publicvoid onReceive(Context c,Intent intent){
         List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
         wifis =newString[wifiScanList.size()];
         for(int i =0; i < wifiScanList.size(); i++){
            wifis[i]=((wifiScanList.get(i)).toString());
         }

         list.setAdapter(newArrayAdapter<String>(getApplicationContext(),
         android.R.layout.simple_list_item_1,wifis));
      }
   }

}
Following is the modified content of the xml res/layout/activity_main.xml.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity">

   <ListView
      android:id="@+id/listView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:drawSelectorOnTop="false"
      android:background="@android:color/background_dark"
      android:listSelector="@android:color/darker_gray">

   </ListView></RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.wifi"
   android:versionCode="1"
   android:versionName="1.0">

   <uses-sdk
      android:minSdkVersion="14"
      android:targetSdkVersion="17"/>

   <uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
   <uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE"/>

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme">
      <activity
         android:name="com.example.wifi.MainActivity"
         android:label="@string/app_name">
         <intent-filter>
            <actionandroid:name="android.intent.action.MAIN"/>

            <categoryandroid:name="android.intent.category.LAUNCHER"/>
         </intent-filter>
      </activity>
    <activity
         android:name="com.example.wifi.ListWifiActivity"
         android:label="@string/title_activity_list_wifi">
      </activity>
   </application></manifest>

Let's try to run your WIFI application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Anroid Wi-Fi Tutorial
Select your mobile device as an option and then check your mobile device which will display your mobile screen filled with wireless networks around you. It is shown below:
Anroid Wi-Fi Tutorial
Note the information that has been returned to you. It contains much information about each of the wireless network detected.
undefined

[Android Useful Examples] Android Widgtets Tutorial

 widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your homescreen in order to quickly access them. You have probably seen some common widgets , such as music widget , weather widget , clock widget e.t.c
Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets.

Widget - XML file

In order to create an application widget , first thing you need is AppWidgetProviderInfo object, which you will define in a seperate widget XML file. In order to do that, right click on your project and create a new folder called xml. Now right click on the newly created folder and create a new XML file. The resource type of the XML file should be set to AppWidgetProvider. In the xml file, define some properties which are as follows:
<appwidget-provider 
   xmlns:android="http://schemas.android.com/apk/res/android" 
   android:minWidth="146dp" 
   android:updatePeriodMillis="0" 
   android:minHeight="146dp" 
   android:initialLayout="@layout/activity_main"></appwidget-provider>

Customize Joomla Extensions With Override

We all know that Joomla is a fantastic CMS for building professional websites. The JED (Joomla Extension Directory) is full of components, modules and plugins that can add almost any type of functionality to any Joomla site. That's great and all but what if you find a component or module that gives the functionality needed but the output and layout is not exactly what you want? A big mistake that some developers and webmasters make is going in and editing the core code of an extension. Joomla makes it easy by allowing overrides.

What is an Override?

An override is a copy of an extensions layout/template file that is placed in your Joomla template directory. You can then customize it to your liking. The difference with doing this as oppose to just editing the file in the extension directory is that when you upgrade Joomla or the extension, your changes will not be replaced with the new versions. Joomla knows to look in the overridden file first, then the actual extensions file.
undefined

How do I Create an Override?

Creating an override is easy. For the sake of this tutorial, let's say that we want to edit the output of the login page. By default, the login page has 3 links in an unordered list (forgot password, forgot username and don't have an account).
Default component frontend
For the sake of this tutorial, let's say that we do not want the last "Don't have an account" link and we also do not want them in a list, we just want the 2 other links side by side. The changes we make do not really matter at this point. It is just to show you how an override works. By default, Joomla uses the com_users component to handle login and registration. The com_users component has multiple views/layouts. We can see them by going tojoomlasite/components/com_users/views
Component view files
You can see there are 5 different views. We want to edit the login page so we want the loginfolder/view. If you click on that, you will then see a tmpl folder. This is the template for this particular view. In the tmpl folder is where the layout files are located. Just about all component and module tmpl folders have a default.php file. Some components such as this have additional template files. The Users component login view has default.php, default_login.php anddefault_logout.php.
Component layout files
The default_login.php folder is the one we need to edit the login form page. So we need to take that file and place it into the Joomla template folder structure. Go to your main Joomla template folder. This would be in joomlasite/templates/yourtemplatname. You need to create a new folder called html. In that html folder, create another called com_users and then in that, one more folder called login. This is where you want to place the default_login.php file that you copied. So the full path would bejoomlasite/templates/yourtemplatename/html/com_users/login/default_login.php

Editing the default_login.php File

So now if we make some changes and save the default_login.php override file, Joomla will look to this file first. Let's make the small change of removing the list and the last link In the newdefault_login.php file, you will see the following code
Default component code
It is the unordered list with the 3 links. Let's edit this by removing the list tags and getting rid of the 3rd link along with the if statement. So it will look like this
New component frontend
Now save the file and go back to your frontend login page.
New component frontend
You can now see that the list formatting and the 3rd link are both gone. So now if you update Joomla core files or update the com_users component, this change would stay with the site as oppose to just being written over. This is extremely useful in Joomla web development. You can do this with any component or module that follows the standard Joomla structure. Do you have any extensions in mind that you would like to tweak to your liking? Let us know in the comment section