Selasa, 12 April 2011

How to Chek Net Connection in Emulator Programetically


In mobiles inter net speed is very slow,  and we can get net connection through Blue Tooth
or WI FI .
so before perform  any  net Work based applications first we check net is properly working or 
 not .
in emulator for Enable and disable net work short cut key is : F8


Android API provides Excellent Packages for Net Work Based Applications 

 ↳ android.net.ConnectivityManager :
================================

Class that answers queries about the state of network connectivity. It also notifies applications when network connectivity changes. Get an instance of this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE).

The primary responsibilities of this class are to:

   1. Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
   2. Send broadcast intents when network connectivity changes
   3. Attempt to "fail over" to another network when connectivity to a network is lost
   4. Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks

context=getApplicationContext();       
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);




public boolean getBackgroundDataSetting () :
------------------------------------------
    Returns the value of the setting for background data usage. If false, applications should not use the network if the application is not in the foreground.     Developers should respect this setting, and check the value of this before performing any background data operations.
   
    All applications that have background services that use the network should listen to ACTION_BACKGROUND_DATA_SETTING_CHANGED.
    Returns
    * Whether background data usage is allowed.




 ↳android.telephony.TelephonyManager
===================================

Provides access to information about the telephony services on the device. Applications can use the methods in this class to determine telephony services and states, as well as to access some types of subscriber information. Applications can also register a listener to receive notification of telephony state changes.

You do not instantiate this class directly; instead, you retrieve a reference to an instance through Context.getSystemService(Context.TELEPHONY_SERVICE).

Note that access to some telephony information is permission-protected. Your application cannot access the protected information unless it has the appropriate permissions declared in its manifest file. Where permissions apply, they are noted in the the methods through which you access the protected information.

TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);



↳android.net.NetworkInfo
========================
Describes the status of a network interface of a given type (currently either Mobile or Wifi). 









    Before Running Any Applications in Emulator First we should add permissions to Manifest File 
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


CheckNet.java :
============
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class CheckNet extends Activity {
    private Context cuContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            cuContext = getApplicationContext();
            ConnectivityManager connectivityManager = (ConnectivityManager) cuContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            TelephonyManager telephonyManager = (TelephonyManager) cuContext
                    .getSystemService(cuContext.TELEPHONY_SERVICE);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            NetWorkStatus ns = new NetWorkStatus(connectivityManager,
                    telephonyManager);
            if (ns.isNetWorkAvilable()) {
                Toast.makeText(getApplicationContext(), "Connected ",
                        Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(getApplicationContext(), " not Connected ",
                        Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            Log.w(" error ", e.toString());
        }

    }
}



NetWorkStatus.java 
--------------------------------

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

public class NetWorkStatus {
    ConnectivityManager mConnectivityManager;
    TelephonyManager mTelephonyManager;
    public NetWorkStatus(ConnectivityManager connectivityManager,
            TelephonyManager telephonyManager) {
        mConnectivityManager = connectivityManager;
        mTelephonyManager = telephonyManager;
    }

    public boolean isNetWorkAvilable() {
        NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
        if (info == null || !mConnectivityManager.getBackgroundDataSetting()) {
            return false;
        }
        int netType = info.getType();
        int subtype = info.getSubtype();
        Log.w(" network values ", " netType :" + netType + "  subtype "
                + subtype + " ");
        if (netType == ConnectivityManager.TYPE_WIFI) {
            return info.isConnected();
        } else if (netType == ConnectivityManager.TYPE_MOBILE
                && subtype == TelephonyManager.NETWORK_TYPE_UMTS
                && !mTelephonyManager.isNetworkRoaming()) {
            return info.isConnected();
        } else {
            return false;
        }

    }

}
 



If Connected Net Sucessfully



If Net Is Not Connected         


  For Downloading Source Click Me

Rabu, 06 April 2011

How to send email from your application

Today we'll create an easy email sender application.
First of all we need to create a layout to set the address, the subject and email body box.
      
Note :
===
1-> when we are developing Any internet based application we should add 
 below tag in manifest file :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

2-> this application won't work in Emulator

3->  our device should be contained net internet connection 

                                                                                                                                                               

public static final String ACTION_SEND


Activity Action: Deliver some data to someone else. Who the data is being delivered to is not specified; it is up to the receiver of this action to ask the user where the data should be sent.

When launching a SEND intent, you should usually wrap it in a chooser (through createChooser(Intent, CharSequence)), which will give the proper interface for the user to pick how to send your data and allow you to specify a prompt indicating what they are doing.

Input: getType() is the MIME type of the data being sent. get*Extra can have either a EXTRA_TEXT or EXTRA_STREAM field, containing the data to be sent. If using EXTRA_TEXT, the MIME type should be "text/plain"; otherwise it should be the MIME type of the data in EXTRA_STREAM. Use */* if the MIME type is unknown (this will only allow senders that can handle generic data streams).

Optional standard extras, which may be interpreted by some recipients as appropriate, are: EXTRA_EMAIL, EXTRA_CC, EXTRA_BCC, EXTRA_SUBJECT.

Output: nothing.
Constant Value: "android.intent.action.SEND"


main.xml file :
------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/LinearLayout02"     android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText android:layout_width="wrap_content"         android:layout_height="wrap_content" android:width="170dip"
            android:id="@+id/emailaddress"></EditText>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/emailaddress"
            android:text="Email address"></TextView>
    </LinearLayout>
    <LinearLayout android:id="@+id/LinearLayout03"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:width="170dip"
            android:id="@+id/emailsubject"></EditText>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/emailsubject"
            android:text="Subject"></TextView>
</LinearLayout>
<EditText android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:lines="5" android:width="300dip"
        android:id="@+id/emailtext"></EditText>
    <Button
    android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:id="@+id/emailsendbutton"  android:text="Send" android:width="150dip">
        </Button>
</LinearLayout>


Email.java :
-----------------
package sra.emia;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Email extends Activity {
    Button send;
    EditText address, subject, emailtext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        send = (Button) findViewById(R.id.emailsendbutton);
        address = (EditText) findViewById(R.id.emailaddress);
        subject = (EditText) findViewById(R.id.emailsubject);
        emailtext = (EditText) findViewById(R.id.emailtext);
        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // getting values and stored in particula intent
                final Intent emailIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[] { address.getText().toString() });
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        subject.getText());
                Email.this.startActivity(Intent.createChooser(emailIntent,
                        "Send mail..."));
            }
        });
    }
}
When we are running our app in Emulator we will get this type of message ( means not working )



  
When we use Device we can sent Sucessfully with specifed id by our device holder 

    







 

Executing a HTTP POST Request with HttpClient

//  here i am explaining how to send some data to server

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class SendInfo {
    private boolean isPosted = false;

    public SendInfo() {
    }

    public boolean PostData() {
        try {
  
            HttpClient mClient = new DefaultHttpClient();
            HttpPost mpost = new HttpPost("http://www.webimm.com/");
         List<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>(2);
            nameValuepairs.add(new BasicNameValuePair("101",
                    "sravankumar@vizser.com"));
            Log.w("send info1 ", "send info1");
            nameValuepairs.add(new BasicNameValuePair("102",
                    "suryaprakash@vizser.com"));
            Log.w("send info2 ", "send info2");
            mpost.setEntity(new UrlEncodedFormEntity(nameValuepairs));
            HttpResponse responce = mClient.execute(mpost);
            HttpEntity entity = responce.getEntity();
           BufferedReader buf = new BufferedReader(new InputStreamReader(
                    entity.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = buf.readLine()) != null) {
                Log.w(" data is ", line);
            }
            isPosted = true;
            return isPosted;
        } catch (UnsupportedEncodingException e) {
         
            Log.w(" error ", e.toString());
        } catch (Exception e) {

            Log.w(" error ", e.toString());
        }

        return isPosted;

    }

}