Wednesday, 29 April 2015

If Internet Available on device then which ( WiFi || Mobile Data )


Required both permission in AndroidManifest.xml :

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


Code Snippets :

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( "Alert " ,"Wifi connected: " + isWifiConn);
Log.d( "Alert ","Mobile connected: " + isMobileConn);


Get Available Space on sdcard if sdcard available


/**
  * do this only *after* you have checked external storage state:
  **/

   File extdir              =  Environment.getExternalStorageDirectory();
   StatFs stats            =  new StatFs(extdir.getAbsolutePath());
   int availableBytes =  stats.getAvailableBlocks() * stats.getBlockSize();

   Log.d("Available Space :", String.valueOf(availableBytes) + "Bytes");  


/**
 * Check SDCard Available Or Not
 **/

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(isSDPresent)
{
  // yes SD-card is present
}
else
{
 // No Sdcard Is Present
}

HOW TO READ FILE FROM ASSET FOLDER FOR GET CONTENT ?

Steps :

1. Place your text file in the /assets directory under the Android project.
2. Use AssetManager class to access it.

Code Snippets :

         AssetManager am = context.getAssets();
InputStream is       = am.open("test.txt");

OR

 1you can also put the file in the /res/raw directory,
 2.where the file will be indexed and is accessible by an id in the R file:

InputStream is = getResources().openRawResource(R.raw.test);

HOW TO KNOW APPLICATION ALREADY INSTALLED OR NOT ?

Code snippets :

public static boolean isPackageInstalled(String packagename, Context context)
{
try 
{
PackageManager pm = context.getPackageManager();

/*
* PackageManager.GET_ACTIVITIES
* PackageInfo flag: return information about activities in the package in activities.
*/
PackageInfo packageInfo =
                                       pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
if(packageInfo != null)
return true;
else
return false;

        catch (NameNotFoundException e) 
{
return false;
}
}

Get IP Address And MAC Address of WiFi Connected Router


/**
 *     Get IP Address of WiFi Connected Router`s in Android Application
 **/

 public static String getipaddressofwifirouterconnected(Context con)
{
      final WifiManager manager = (WifiManager)con.getSystemService(WIFI_SERVICE);
      final DhcpInfo dhcp = manager.getDhcpInfo();
      final String address = Formatter.formatIpAddress(dhcp.gateway);
 
      return address;
}

/**
 *    Get Mac Address of WiFi connected Router`s in Android Application
 **/

public static String getmacaddressofwificonnected(Context context)
{
      final WifiManager manager = (WifiManager)context.getSystemService(WIFI_SERVICE);
      WifiInfo wifiInfo        = manager.getConnectionInfo();
      String macaddress        = wifiInfo.getBSSID();

      return macaddress;
}

Thursday, 23 April 2015

Check Internet Connection On-Off in Android Application : code snippets

       /*
* Check Internet Connection
*/

public static boolean checkConnection(Context c)
{
try
{
ConnectivityManager mConnectivityManager  = (ConnectivityManager)                                                                              c.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager telephonyManager = (TelephonyManager)
                                                       c.getSystemService(Context.TELEPHONY_SERVICE);

if (mConnectivityManager.getNetworkInfo
                                                                 (ConnectivityManager.TYPE_WIFI).isConnected() ||
        telephonyManager.getDataState()  ==
                                                                  TelephonyManager.DATA_CONNECTED)
return true;
else
return false;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}

Check External SD-Card Available or Not : code snippets

 /*
* Check External SDCARD Is Inserted OR Not
*/

public static boolean isExternalSDCardAvailable(Context c)
{
boolean flagExSdcard = false;
try
{
String exsdcard_path = "/sys/block/mmcblk1";
File file = new File(exsdcard_path);

String memBlk = null;

if (file.exists() && file.isDirectory())
{
flagExSdcard = true;
}

if (flagExSdcard == false)
{
Map<String, File> externalLocations = ExternalStorage
.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations
.get(ExternalStorage.EXTERNAL_SD_CARD);

if (externalSdCard != null)
{
flagExSdcard = true;
}
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}

return flagExSdcard;
}

Android Executing Shell Commands – Example

Executing Shell commands is useful to perform deep operating system operations.
In this tutorial we are going to see how to execute Linux shell commands with your Android Application.


Creating Layout

Our main layout consists of a EditText widget to get shell command as input. It also has a Button widget to execute the command. It also has a TextView widget to display the output of the command which is executed.

activity_main.xml

<LinearLayout 
    xmlns: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:orientation="vertical"
    android:layout_gravity="center"
    tools:context=".MainActivity" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textAlignment="center"
        android:text="Shell Executer" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt"
        android:hint="Example - ls" />
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Execute" />
     <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/out"
        android:textAlignment="textStart" />
</LinearLayout>

Creating Activity

Before proceeding to MainActivity class we need to create ShellExecuter class which has the function to execute shell commands.
It has a function Executer which has a parameter command. The command is executed using the function Runtime.getRuntime().exec(command). 
Then we use BufferReader to read the output and parse it.

ShellExecuter.java
package com.example.androidshell;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShellExecuter 
{
   public ShellExecuter() 
   { }
   public String Executer(String command) 
   {
      StringBuffer output = new StringBuffer();
      Process p;
      try 
      {
         p = Runtime.getRuntime().exec(command);
         p.waitFor();
         BufferedReader reader = 
         new BufferedReader(new  InputStreamReader(p.getInputStream()));
              String line = "";    
          while ((line = reader.readLine())!= null) 
          {
             output.append(line + "\n");
          }
      } 
      catch (Exception e) 
      {
        e.printStackTrace();
      }
      String response = output.toString();
      return response;
    }
}
In MainActivity we are initially importing the layout items. When the button is pressed the Executer() function is invoked and the output is displayed in a TextView.

MainActivity.java

package com.example.androidshell;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import com.example.androidshell.ShellExecuter;

public class MainActivity extends Activity 
{
  EditText input;
  Button btn;
  TextView out;
  String command;
  @Override
  protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    input = (EditText)findViewById(R.id.txt);
    btn = (Button)findViewById(R.id.btn);
    out = (TextView)findViewById(R.id.out);
    btn.setOnClickListener(new View.OnClickListener() 
{
      @Override
      public void onClick(View arg0) 
{
        // TODO Auto-generated method stub
        ShellExecuter exe = new ShellExecuter();
        command = input.getText().toString();
        String outp = exe.Executer(command);
        out.setText(outp);
        Log.d("Output", outp);
      }
    });
  }

}