Sunday, March 25, 2012

Send an sms using Android

Create a new project in android and name it "smsSend". Give it a package name "com.send.sms". Set activity as "SmsSendActivity"

In this application for convenience, I created an activity window like the following.



To create  the above screen, select the "res->layout->main.xml" and paste the following code their.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />



    <EditText
        android:id="@+id/editTextPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:phoneNumber="true" >

    </EditText>

    <TextView
        android:id="@+id/textViewSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/editTextSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:lines="5" />



    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Send" />

</LinearLayout>

Then  the Android manifest file should include a permission to send sms. For this select "AndroidManifest->Permissions->Add-> UsesPermission" Select "Android.Permission.SEND_SMS". and save project.
See tha image below...


Now select the "SmsSendActivity,java" and paste the code below in their.

package com.send.sms;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SmsSendActivity extends Activity {

    Button buttonSend;
    EditText textPhoneNo;
    EditText textSMS;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        buttonSend = (Button) findViewById(R.id.buttonSend);
        textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
        textSMS = (EditText) findViewById(R.id.editTextSMS);

        buttonSend.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                String phoneNo = textPhoneNo.getText().toString();
                String sms = textSMS.getText().toString();

                try {
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(phoneNo, null, sms, null, null);
                    Toast.makeText(getApplicationContext(), "SMS Sent!",
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }

            }
        });
    }
}

Thats it...  Make an .apk file of this program and install it in android device..

Wish you all the best....

Sunday, March 18, 2012

How to install your android application in mobile- How to create a .apk file using Eclipse

In Eclipse "Package Explorer" window, Right-click on your project select Android Tools->Export Signed Application Package..





The Next window will contain your project name in the text field. Now click "Next"





In the next window Select any location and give a name for the file you want to write. and click "save"





 Now give a password with number of characters not less than 6.




In the next window give suitable values and click "Next"; for example see the image below... the validity should be at least 25 years..



In the next window select a destination folder in which the .apk file should be stored ; and click "save" . Then click "Finish".


Now go to the folder where you saved the .apk file. Transfer this file to any android mobile through usb or, sd card or some other ways. 

Download any "application installer" from android market and open it. This application will show all .apk files including your project. Now click on it and install.....


Wish you the best......


Sunday, March 11, 2012

How to get your location using Android; GPS locator using android


This is an application which locates where you are. It uses your mobile GPS provider, or you GPRs connectivity or even the WiFi connectivity you can access.


First  Start up your eclipse, Go to File->New-> Project -> Android Project. Then click "Next".

Give project name, "edayansLocator". Click "Next". Select android version you have (I have selected Android 4.3).  and click "Next".

On the next window give  package name as "com.edayans.locator". As shown below and click "Finish".



Now select  "res -> values-> strings.xml". open it and click "Add" button and select "String". Then click "OK".   See the images below.




Give  Name as "getLocation" and Value as "Get My Location"; As shown below.


Now select "res -> Layout-> main.xml". Switch to graphical layout(indicated by  yellow color arrow in the image below).

From the "Form Widgets" in the panel on the left side, select "Button " (indicated by red arrow) and drag it to screen. (See image below).




Now right click on the "Button" and click on "Edit Text..." and select "getLocation" from the new window and click "OK". see images below.





Now again Right click on the Button and go to "Other properties -> All By Name -> On Click " ; in the new window type "onClickDoThis".





Now go to "src -> com.edayans.locator ->EdayansLocatorActivity.java " the  copy and paste  the code given below on their.


package com.edayans.locator;

import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class EdayansLocatorActivity extends Activity {
    /** Called when the activity is first created. */
   
    private String provider;
    private LocationManager locationManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickDoThis(View v) {
       
        showCurrentLocation();
    }
    protected void showCurrentLocation() {
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            double lat = location.getLatitude();
            double lon = location.getLongitude();
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    lon, lat);
            Toast.makeText(EdayansLocatorActivity.this, message,
                    Toast.LENGTH_LONG).show();

        } else {
            Toast.makeText(EdayansLocatorActivity.this, "no location available",
                    Toast.LENGTH_LONG).show();
        }
    }

}


Now Select "AndroidManifest.xml" from the panel and got to "Permissions" (indicated by red and brown arrows) and click "Add" button (on the upper right side in the image).  Then  select "Uses Permission" and click "OK".





Then select "android.permission.ACCESS_COARSE_LOCATION". See the image below...


 


Then add  "android.permission.ACCESS_FINE_LOCATION", and
 also "android.permission.ACCESS_INTERNET".




Now take a look what we have added;

ACCESS_COARSE_LOCATION : This allows you to access the location through a network like  WiFi, Cell-ID etc..

ACCESS_FINE_LOCATION : This allows you to access the location through GPS.

Now save the project and install the .apk file to any android mobile. click on the button and get your location.


Note:  This application is not for running on any simulator. To run this application on simulator we have to provide a "mock" location and also a permission to use "MOCK_LOCATION". But any way you can install this application on any android device and feel it.


wish you all the best.....


Thursday, March 1, 2012

Android- Sample calculator program

Hi, This is a sample program in android. It explains basic entities and programming concepts of android. Try this one.. 
Start eclipse IDE with ADT plugin. 

First select "File->New->Project->Android->Android Project" and click "Next".
In the new screen type in a Project Name as shown below.




 On the new screen Select the android platform in which you want to  create your application. See the image below.





Click "Next" here. You will get a new window..Give a package name their. Package name must be of two folder name separated with a dot. See the image below.

 
Click "Finish" Button. So you can see your project is on the "Package Explorer" panel on the left side of your Eclipse window.  Click on the project now. That will contain many folders as below.


 1. The "src" folder will contain your package (com.edayans here) in which the the Activity is located.
 2. The "gen" folder will contain a "R.java " file. This is automatically created and we need not to alter it.
 3. The "res" folder will contain resources for the application.
       A.  "drawable" folders will contain different images you want to use in your program.
       B.  The "layout-> main.xml" will provide you graphical User Interface for your project.
       C.  The  "values->strings.xml" file will be provided with different resourced like string, color etc.
4. The "AndroidManifest.xml" file will keep all records like application name, hardware access permissions  etc..

 Now  we can take the "values->strings.xml"  file. It will be of two form. "Resources" and  "strings.xml" file. Click on the Resources and you will see a window like following.

 Select the "hello(String)" from the left panel and click "Remove.." button. (You may notice an error has invoked at other files. leave it for now. We can fix it later).
 Now we can add our own resources. For that click "Add..." button. Select "string"  item from the new window and click "OK".
Now on the right panel you will see "Name" and "Value" fields. Type in the corresponding fields as follows.
Name: sum
Value: Calculate Sum

For more details see the image below.

 

Also add another String as follows

Name: result
Value: Result

Save the work till now. (Press ctrl+s). Now go to "layout-> main.xml". You can see two tabs at the bottom left corner named "Graphical Layout" and "main.xml". Select the Graphical layout. You will see a window like below.

Click on the "@string/hello" field and delete it. Then we can save our project again. (So the error is now fixed).

Now from the "palette" panel from the left, select "Text Fields" and drag "editText" to the screen. ("editText" may be noted with letters "abc" on it.) Do this twise to add another "editText" to the screen. So you have two "editText" on your screen.
 
Then add a "textview"  from the "Form Widgets" by dragging it to the screen.
 Now drag a "button" from the "Form Widgets" to the screen.  Now the screen will look like this.

Now we have to specify each fields properties. First we begin with Button. Right click on it and select "EditText". In the new window select "sum" and click "ok"..


 
Then right click on the "textview" select ""EditText". In the new window select "result" and click "ok".

Now the screen will look like follows.


Now right click again on button go to "Other Properties -> All by name -> onClick" set  value "onMyClickdoThis". (This wiil be used later for our onclick function ).

After that right click on the "editText" field. go to "Other Properties -> All by name ->Input Type" set them as "Number Signed" and "Number Desimal". Do this for both "editText" fields.

Now right click on "editText" again and set "Layout Width=Match Parent" and "Layout Height=Wrap Content".
Do this for both "editText" fields and also for "textView".

Now save the project again.

Now go to "src " folder and select "EdayansCalculatorActivity.java". Copy  the code given below and paste their.

package com.edayans;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EdayansCalculatorActivity extends Activity {
    /** Called when the activity is first created. */
    private EditText text1;
    private EditText text2;
    private TextView txtResult;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        text1 = (EditText) findViewById(R.id.editText1);
        text2 = (EditText) findViewById(R.id.editText2);
        txtResult=(TextView)findViewById(R.id.textView1);
    }
    public void  onMyClickdoThis (View view) {
        switch (view.getId()) {
        case R.id.button1:
            if ((text1.getText().length() == 0) ||(text2.getText().length() == 0)) {
                Toast.makeText(this, "Please enter a valid number",
                        Toast.LENGTH_LONG).show();
                return;
            }else{
                int f_num=Integer.parseInt(text1.getText().toString());
                int s_num=Integer.parseInt(text2.getText().toString());
                txtResult.setText(String.valueOf(f_num+s_num));
               
            }
            break;
        }
}
}

Then right click on the project folder on the left panel. Then select "Run As -> Android Application". (See the image below).


Wait for some seconds, the emulator will be loaded soon. See the image below.



Click on the "lock" button and drag it to right side.(In the image below, it is indicated by  red arrow). Wait  for a second, your application will be launched.

 Note: The emulator varies with android platform and API version etc. Your emulator may not be like the above. Even if that, you have to unlock the emulator.



Then try it, give numbers to the text Fields and click the button "Calculate Sum". You got it.





Android- Activity, Services Introduction of concepts


              Android is a java-based operating system that runs on Linux kernel. Android applications are developed using java and also uses an XML based User Interface. The basic building blocks of android includes
1.Activity
2.Service
3.Broadcast Receiver
4.Content Providers

           Activity is the basic building block of visible applications. Every application is composed of an activity or set of activities. Also every screen in an application is an individual activity.
          Services are used to provide background tasks. They do not give any UI.
          Broadcast Receivers are capable of receiving and respond to any announcements by an Intent or system. an Intent is a message passed between components like APIs(but not exactly).
          Content Providers gives a set of data to applications. They can supply data to other applications.

Now to develop an android application we need following tools,
1. JDK- Since we use java for android development-download from here- http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. Android SDK-download from here-http://developer.android.com/sdk/index.html
3. An IDE with Android plugin (Preferably Eclipse)-download from here-http://www.eclipse.org/downloads/

Read the installation manuals and install it. After installing Android SDK manager and AVD manager we can start our own android program.