Wednesday 14 December 2011

Audio Recording part-2


EnvironmentRecorder.java 


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

public class EnvironmentRecorder {
        private static final int RECORDER_BPP = 16;
        private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
        private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
        private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
        private static final int RECORDER_SAMPLERATE = 44100;
        private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
        private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
     
        private AudioRecord recorder = null;
        private int bufferSize = 0;
        private Thread recordingThread = null;
        private boolean isRecording = false;
     
       
        public EnvironmentRecorder(){
       
         
           try{
            bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);
           }catch (Exception e) {
e.printStackTrace();
}
       
        }
   
     
     
     
     
     
     
        private String getFilename(){
                String filepath = Environment.getExternalStorageDirectory().getPath();
                File file = new File(filepath,AUDIO_RECORDER_FOLDER);
             
                if(!file.exists()){
                        file.mkdirs();
                }
             
                return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
        }
     
        private String getTempFilename(){
                String filepath = Environment.getExternalStorageDirectory().getPath();
                File file = new File(filepath,AUDIO_RECORDER_FOLDER);
             
                if(!file.exists()){
                        file.mkdirs();
                }
             
                File tempFile = new File(filepath,AUDIO_RECORDER_TEMP_FILE);
             
                if(tempFile.exists())
                        tempFile.delete();
             
                return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
        }
     
       public void startRecording(){
                recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                                RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
             
                recorder.startRecording();
             
                isRecording = true;
             
                recordingThread = new Thread(new Runnable() {
                     
                        @Override
                        public void run() {
                                writeAudioDataToFile();
                        }
                },"AudioRecorder Thread");
             
                recordingThread.start();
        }
     
        private void writeAudioDataToFile(){
                byte data[] = new byte[bufferSize];
                String filename = getTempFilename();
                FileOutputStream os = null;
             
                try {
                        os = new FileOutputStream(filename);
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
             
                int read = 0;
             
                if(null != os){
                        while(isRecording){
                                read = recorder.read(data, 0, bufferSize);
                             
                                if(AudioRecord.ERROR_INVALID_OPERATION != read){
                                        try {
                                                os.write(data);
                                        } catch (IOException e) {
                                                e.printStackTrace();
                                        }
                                }
                        }
                     
                        try {
                                os.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
     
       public void stopRecording(){
                if(null != recorder){
                        isRecording = false;
                     
                        recorder.stop();
                        recorder.release();
                     
                        recorder = null;
                        recordingThread = null;
                        copyWaveFile(getTempFilename(),getFilename());
                        deleteTempFile();
                }
             
             
        }

        private void deleteTempFile() {
                File file = new File(getTempFilename());
             
                file.delete();
        }
     
        private void copyWaveFile(String inFilename,String outFilename){
                FileInputStream in = null;
                FileOutputStream out = null;
                long totalAudioLen = 0;
                long totalDataLen = totalAudioLen + 36;
                long longSampleRate = RECORDER_SAMPLERATE;
                int channels = 2;
                long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels/8;
             
                byte[] data = new byte[bufferSize];
             
                try {
                        in = new FileInputStream(inFilename);
                        out = new FileOutputStream(outFilename);
                        totalAudioLen = in.getChannel().size();
                        totalDataLen = totalAudioLen + 36;
                     
                        //AppLog.logString("File size: " + totalDataLen);
                     
                        WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
                                        longSampleRate, channels, byteRate);
                     
                        while(in.read(data) != -1){
                                out.write(data);
                        }
                     
                        in.close();
                        out.close();
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }

        private void WriteWaveFileHeader(
                        FileOutputStream out, long totalAudioLen,
                        long totalDataLen, long longSampleRate, int channels,
                        long byteRate) throws IOException {
             
                byte[] header = new byte[44];
             
                header[0] = 'R';  // RIFF/WAVE header
                header[1] = 'I';
                header[2] = 'F';
                header[3] = 'F';
                header[4] = (byte) (totalDataLen & 0xff);
                header[5] = (byte) ((totalDataLen >> 8) & 0xff);
                header[6] = (byte) ((totalDataLen >> 16) & 0xff);
                header[7] = (byte) ((totalDataLen >> 24) & 0xff);
                header[8] = 'W';
                header[9] = 'A';
                header[10] = 'V';
                header[11] = 'E';
                header[12] = 'f';  // 'fmt ' chunk
                header[13] = 'm';
                header[14] = 't';
                header[15] = ' ';
                header[16] = 16;  // 4 bytes: size of 'fmt ' chunk
                header[17] = 0;
                header[18] = 0;
                header[19] = 0;
                header[20] = 1;  // format = 1
                header[21] = 0;
                header[22] = (byte) channels;
                header[23] = 0;
                header[24] = (byte) (longSampleRate & 0xff);
                header[25] = (byte) ((longSampleRate >> 8) & 0xff);
                header[26] = (byte) ((longSampleRate >> 16) & 0xff);
                header[27] = (byte) ((longSampleRate >> 24) & 0xff);
                header[28] = (byte) (byteRate & 0xff);
                header[29] = (byte) ((byteRate >> 8) & 0xff);
                header[30] = (byte) ((byteRate >> 16) & 0xff);
                header[31] = (byte) ((byteRate >> 24) & 0xff);
                header[32] = (byte) (2 * 16 / 8);  // block align
                header[33] = 0;
                header[34] = RECORDER_BPP;  // bits per sample
                header[35] = 0;
                header[36] = 'd';
                header[37] = 'a';
                header[38] = 't';
                header[39] = 'a';
                header[40] = (byte) (totalAudioLen & 0xff);
                header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
                header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
                header[43] = (byte) ((totalAudioLen >> 24) & 0xff);

                out.write(header, 0, 44);
        }
     
       
}

Send Email Example

SendEmailAttachmentActivity.java



package com.android.sendemailatattachment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class SendEmailAttachmentActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("image/jpeg");
        //sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Photo");
        sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/shortcut.jpeg"));
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Enjoy the photo");
        startActivity(Intent.createChooser(sendIntent, "Email:"));


    }
}

Show Gps Data

ShowGpsDataActivity.java





package com.android.showgpsdata;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;






import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;


public class ShowGpsDataActivity extends Activity {
private TextView txtData;

public static double lat = 0.0, longi = 0.0, gps_lat = 0.0, gps_long = 0.0,
gps_alt = 0.0;
public static float gps_speed = 0.0f;
long gps_time = 0 ;

private LocationManager locationManager;
private LocationListener locationListener;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        txtData=(TextView)findViewById(R.id.txtData);


        txtData.setTextSize(20);
        txtData.setTextColor(Color.BLACK);
        txtData.setBackgroundColor(Color.WHITE);
        txtData.setText(Html.fromHtml("<strong><b>GPS_Time:-</b><br>"+"\n"+getGpsTime(gps_time)+"<br><br><b>GPS_Latitude:- </b><br>"+gps_lat+"<br><br><b>GPS_Longitude:- </b><br>"+gps_long+"<br><br><b>GPS_Altitude:- </b><br>"+gps_alt+"<br><br><b>GPS_Speed:- </b><br>"+gps_speed+" Meter/Second"));
        try {
// ---use the LocationManager class to obtain GPS locations---


locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


locationListener = new MyLocationListener();


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener);

} catch (Exception e) {
String s = e.toString();
s = "";
}


    }
   
    private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
if (loc != null) {
gps_time = loc.getTime();
gps_lat = loc.getLatitude();
gps_long = loc.getLongitude();
gps_speed = loc.getSpeed();
gps_alt = loc.getAltitude();

 txtData.setText(Html.fromHtml("<b>GPS_Time:-</b><br>"+"\n"+getGpsTime(gps_time)+"<br><br><b>GPS_Latitude:- </b><br>"+gps_lat+"<br><br><b>GPS_Longitude:- </b><br>"+gps_long+"<br><br><b>GPS_Altitude:- </b><br>"+gps_alt+"<br><br><b>GPS_Speed:- </b><br>"+gps_speed+" Meter/Second"));
} else {
gps_time = 0;
gps_lat = 0.0;
gps_long = 0.0;
gps_speed = 0.0f;
gps_alt = 0.0;
}
}


@Override
public void onProviderDisabled(String provider) {
gps_time = 0;
gps_lat = 0.0;
gps_long = 0.0;
gps_speed = 0.0f;
gps_alt = 0.0;
}


@Override
public void onProviderEnabled(String provider) {


}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
gps_time = 0;
gps_lat = 0.0;
gps_long = 0.0;
gps_speed = 0.0f;
gps_alt = 0.0;
}
}


    public String getGpsTime(long gps_time) {
if (gps_time != 0) {
// gps_time = Math.abs(gps_time - System.currentTimeMillis());


DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss a");


Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(gps_time);
return formatter.format(calendar.getTime());
} else
return String.valueOf(gps_time);
}


}


Internal Database Example

TestDemoActivity.java



package com.android.testdemo;

import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class TestDemoActivity extends Activity {
private Cursor mCountryCur;
CountryTable conTable;
private StateTable stateTable;
private Cursor mStateCur;
private CityTable cityTable;
private Cursor mCityCur;

private static final String STATE="STATE";
private static final String COUNTRY="COUNTRY";
private static final String CITY="CITY";

private static int backCount=0;

private static String Current=STATE;

private Spinner spnrCountry,spnrState;
private ListView lstCity;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spnrCountry=(Spinner)findViewById(R.id.spnrCountry);
spnrState=(Spinner)findViewById(R.id.spnrState);
lstCity=(ListView)findViewById(R.id.lstCity);
fillCountryList();


spnrCountry.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(TestDemoActivity.this,"List position: "+arg2,Toast.LENGTH_SHORT).show();
fillStateList(arg2+1);

if(lstCity.getChildCount()>1){
lstCity.removeAllViews();
}
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {


}
});

spnrState.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
fillCityList(arg2+1);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(TestDemoActivity.this,"Nothing",Toast.LENGTH_SHORT).show();

}
});

}

private void fillCountryList() {
fetchCountryData();
String[] from = new String[] { CountryTable.COUNTRY_NAME };
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, mCountryCur, from, to);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnrCountry.setAdapter(adapter);
Current=COUNTRY;
}

private void fillStateList(int pos) {
fetchStateData(pos);
String[] from = new String[] { StateTable.STATE_NAME,StateTable._ID };
int[] to = new int[] {android.R.id.text1,};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, mStateCur, from, to);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnrState.setAdapter(adapter);
Current=STATE;
backCount=0;
}

private void fillCityList(int pos) {
fetchCityData(pos);
String[] from = new String[] { CityTable.CITY_NAME };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, mCityCur, from, to);
lstCity.setAdapter(adapter);
}

public void fetchCountryData() {
try {
conTable = new CountryTable(this);
/*conTable.DeleteAllData();
conTable.insert(1, "India");
conTable.insert(2, "U.S.A");
conTable.insert(3, "China");*/

mCountryCur = conTable.fetAllData();
for (int i = 0; i < mCountryCur.getCount(); i++) {
mCountryCur.moveToPosition(i);
Log.i("TEST",
"Country: "
+ mCountryCur.getString(mCountryCur
.getColumnIndex(CountryTable._ID))
+ " : "
+ mCountryCur.getString(mCountryCur
.getColumnIndex(CountryTable.COUNTRY_NAME)));
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void fetchStateData(int pos) {
try {

stateTable = new StateTable(this);
stateTable.DeleteAllData();
stateTable.insert(1, "Gujarat", 1);
stateTable.insert(2, "Maharashtra", 1);
stateTable.insert(3, "Rajasthan", 1);

mStateCur = stateTable.fetchData(pos);
startManagingCursor(mStateCur);
for (int i = 0; i < mStateCur.getCount(); i++) {
mStateCur.moveToPosition(i);
Log.i("TEST",
"state: "
+ mStateCur.getString(mStateCur
.getColumnIndex(StateTable._ID))
+ " : "
+ mStateCur.getString(mStateCur
.getColumnIndex(StateTable.STATE_NAME)));
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void fetchCityData(int pos) {
try {
cityTable = new CityTable(this);
//cityTable.DeleteAllData();
cityTable.insert(10, "Udaipur", 3);
cityTable.insert(11, "Jaipur", 3);
cityTable.insert(12, "Vilasa", 3);

mCityCur = cityTable.fetchData(pos);
startManagingCursor(mCityCur);
for (int i = 0; i < mCityCur.getCount(); i++) {
mCityCur.moveToPosition(i);
Log.i("TEST",
"City: "
+ mCityCur.getString(mCityCur
.getColumnIndex(CountryTable._ID))
+ " : "
+ mCityCur.getString(mCityCur
.getColumnIndex(CityTable.CITY_NAME)));
}
} catch (Exception e) {
e.printStackTrace();
}
}

/*@Override
protected void onListItemClick(ListView l, View v, int pos, long id) {
if(Current.equals(COUNTRY)){
fillStateList(pos+1);
}else if(Current.equals(STATE)){
fillCityList(pos+1);
}else if(Current.equals(CITY)){
//fillCityList();
}

Toast.makeText(this,"List position: "+pos,Toast.LENGTH_SHORT).show();
super.onListItemClick(l, v, pos, id);
}*/

@Override
public void onBackPressed(){
finish();

}
}


CountryTable.java



package com.android.testdemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class CountryTable extends SQLiteOpenHelper {
public static final String DATABASE_NAME="testdemo8";
public static final String TABLE_NAME="country3";

public static final String _ID="_id";
public static final String COUNTRY_NAME="Name";

private SQLiteDatabase mDb;

private static final String CREATE_TABLE="create table if not exists "+TABLE_NAME+" ("+_ID +" integer primary key,"+COUNTRY_NAME +" text)";

public CountryTable(Context context) {
super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
}catch (Exception e) {
e.printStackTrace();
}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

public void insert(int id,String name){
try{
mDb=getWritableDatabase();
ContentValues val= new ContentValues();
val.put(_ID, id);
val.put(COUNTRY_NAME, name);
mDb.insert(TABLE_NAME, null, val);
}catch (Exception e) {
e.printStackTrace();

// TODO: handle exception
}finally{
mDb.close();

}
}

public Cursor fetAllData(){
Cursor c=null;
try{
mDb=getReadableDatabase();
String query = "select * from "+ TABLE_NAME;
//c=mDb.query(TABLE_NAME, new String[]{_ID,COUNTRY_NAME},null, null,null,null,null);
c=mDb.rawQuery(query, null);


}catch (Exception e) {
e.printStackTrace();
}finally{
// mDb.close();
}
return c;
}

public void DeleteAllData(){

try{
mDb=getReadableDatabase();
String query = "delete  from "+ TABLE_NAME;
mDb.execSQL(query);

}catch (Exception e) {
e.printStackTrace();
}finally{

}

}

}


StateTable.java


package com.android.testdemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class StateTable extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "testdemo10";
public static final String TABLE_NAME = "State2";

public static final String _ID = "_id";
public static final String STATE_NAME = "Name";
public static final String COUNTRY_ID = "CountryId";

private SQLiteDatabase mDb;

private static final String CREATE_TABLE = "create table if not exists "
+ TABLE_NAME + " (" + _ID + " integer primary key,"
+ STATE_NAME + " text," + COUNTRY_ID + " INTEGER)";

public StateTable(Context context) {
super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
e.printStackTrace();
}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

public void insert(int id,String name, int Con_id) {
try {
mDb = getWritableDatabase();
ContentValues val = new ContentValues();
val.put(_ID, id);
val.put(STATE_NAME, name);
val.put(COUNTRY_ID, Con_id);
long i=mDb.insert(TABLE_NAME, null, val);
} catch (Exception e) {
e.printStackTrace();

// TODO: handle exception
} finally {
mDb.close();

}
}

public Cursor fetchData(int conid) {
Cursor c = null;
try {
mDb = getReadableDatabase();
String query = "select * from " + TABLE_NAME + " where "
+ COUNTRY_ID + " = " + conid;
c = mDb.rawQuery(query, null);
c.moveToFirst();

} catch (Exception e) {
e.printStackTrace();
} finally {
mDb.close();
}
return c;
}

public void DeleteAllData() {

try {
mDb = getReadableDatabase();
String query = "delete  from " + TABLE_NAME;
mDb.execSQL(query);

} catch (Exception e) {
e.printStackTrace();
} finally {

}

}

}


CityTable.java


package com.android.testdemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class CityTable extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "testdemo11";
public static final String TABLE_NAME = "City2";

public static final String _ID = "_id";
public static final String CITY_NAME = "Name";
public static final String STATE_ID = "StateId";

private SQLiteDatabase mDb;

private static final String CREATE_TABLE = "create table if not exists "
+ TABLE_NAME + " (" + _ID + " integer primary key,"
+ CITY_NAME + " text," + STATE_ID + " INTEGER)";

public CityTable(Context context) {
super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
e.printStackTrace();
}

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

public void insert(int id,String name, int Con_id) {
try {
mDb = getWritableDatabase();
ContentValues val = new ContentValues();
val.put(_ID, id);
val.put(CITY_NAME, name);
val.put(STATE_ID, Con_id);
mDb.insert(TABLE_NAME, null, val);
} catch (Exception e) {
e.printStackTrace();

// TODO: handle exception
} finally {
mDb.close();

}
}

public Cursor fetchData(int conid) {
Cursor c = null;
try {
mDb = getReadableDatabase();
String query = "select * from " + TABLE_NAME + " where "
+ STATE_ID + " = " + conid;
c = mDb.rawQuery(query, null);
c.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
} finally {
mDb.close();
}
return c;
}

public void DeleteAllData() {

try {
mDb = getReadableDatabase();
String query = "delete  from " + TABLE_NAME;
mDb.execSQL(query);

} catch (Exception e) {
e.printStackTrace();
} finally {

}

}

}


main.xml

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




Friday 18 November 2011

ListView Example


import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TestPreprationActivity extends Activity implements
OnItemClickListener, OnMultiChoiceClickListener {

static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania",
"Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
"Antarctica", "Antigua and Barbuda", "Argentina", "Armenia",
"Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Bouvet Island", "Brazil",
"British Indian Ocean Territory", "British Virgin Islands",
"Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cote d'Ivoire",
"Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
"Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia",
"Comoros", "Congo", "Cook Islands", "Costa Rica", "Croatia",
"Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti",
"Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt",
"El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
"Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji",
"Finland", "Former Yugoslav Republic of Macedonia", "France",
"French Guiana", "French Polynesia", "French Southern Territories",
"Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece",
"Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala",
"Guinea", "Guinea-Bissau", "Guyana", };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView listView = new ListView(this);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, COUNTRIES);
// adapter.setDropDownViewResource(android.R.layout.select_dialog_multichoice);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {

//Toast.makeText(TestPreprationActivity.this, "" + listView.getItemAtPosition(arg2),Toast.LENGTH_SHORT).show();

}

});

listView.setOnScrollListener(new OnScrollListener() {

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {

if(scrollState==SCROLL_STATE_FLING){
Toast.makeText(TestPreprationActivity.this,
"Fling",
Toast.LENGTH_SHORT).show();
}else if(scrollState==SCROLL_STATE_IDLE){
Toast.makeText(TestPreprationActivity.this,
"Idle",
Toast.LENGTH_SHORT).show();
}else if(scrollState==SCROLL_STATE_TOUCH_SCROLL){
Toast.makeText(TestPreprationActivity.this,
"touch",
Toast.LENGTH_SHORT).show();
}
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//listView.setItemChecked(firstVisibleItem,true);
for(int i=firstVisibleItem;i<firstVisibleItem+visibleItemCount;i++){
listView.setItemChecked(i,true);
//listView.setItemChecked((firstVisibleItem+5),false);
}


SparseBooleanArray spars=listView.getCheckedItemPositions();
spars.size();
String str="";
for(int i=0;i<spars.size();i++){
str+="\n"+COUNTRIES[spars.keyAt(i)];
}

}
});
// listView.addHeaderView((View)(new TextView(this).setText("Header")));
setContentView(listView);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

}

@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {

}
}

http://ykyuen.wordpress.com/2010/01/03/android-simple-listview-using-simpleadapter/

Wednesday 10 August 2011

DTMF Tone Generator


package com.android.ToneGen;

import android.app.Activity;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class ToneGen extends Activity {
ToneGenerator tone;
Button btnSend;
EditText editTone;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tone = new ToneGenerator(AudioManager.STREAM_DTMF, 100);
        btnSend=(Button)findViewById(R.id.btnSend);
        editTone= (EditText)findViewById(R.id.editTone);
       
        btnSend.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
int no=Integer.parseInt(editTone.getText().toString());
tone.startTone(no,2000);



}
});
       
    }
}

Send MMS Example


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import java.io.File;

public class MMS extends Activity {

// Fields
private String TAG = "MMS";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// To display current window in full screen.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

/**
* See assets/res/layout/mms.xml for this view layout
* definition, which is being set here as the content of our screen.
*/
setContentView(R.layout.mms);

}

/*
* Open Gallery to select image to send on OnClick Event of mmsBtnMMSPic.
*/
public void onClickPicMMS(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);

}


/*
* Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == 0 && resultCode == RESULT_OK) {

// Fetch the path of selected image.
Uri uri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mmsImagPath = cursor.getString(column_index);

//Call the intent to send selected image as MMS.
Intent intent = new Intent(Intent.ACTION_SEND);
File f = new File(mmsImagPath);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); // imageUri set previously
intent.setType("image/jpg");
startActivity(intent);

}
}
}

Dial Number Example


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;





public class DialANumber extends Activity {
  EditText mEditText_number = null;
  LinearLayout mLinearLayout_no_button = null;
  Button mButton_dial = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLinearLayout_no_button = new LinearLayout(this);
    mEditText_number = new EditText(this);
    mEditText_number.setText("5551222");
    mLinearLayout_no_button.addView(mEditText_number);

    mButton_dial = new Button(this);
    mButton_dial.setText("Dial!");
    mLinearLayout_no_button.addView(mButton_dial);
    mButton_dial.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        performDial();
      }
    });

    setContentView(mLinearLayout_no_button);
  }

  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_CALL) {
      performDial();
      return true;
    }
    return false;
  }

  public void performDial(){
    if(mEditText_number!=null){
      try {
        startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mEditText_number.getText())));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }//if
  }
}

Sms Receiver

AndroidManifest.xml

<?xml vers

ion="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        
 
        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>
 
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>



SmsReceiver.java


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
 
public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}