igap Technologies 1 if(!activitycompat.shouldshowrequestpermissionrationale(this, Manifest.permission.READ_CONTACTS)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS, 1); Android Hide Title Bar Example protected void oncreate(bundle savedinstancestate) { requestwindowfeature(window.feature_no_title); //code that displays the content in full screen mode this.getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask Android Screen Orientation Example <activity android:name="com.example.screenorientation.mainactivity" android:label="@string/app_name" android:screenorientation="landscape"> Android ToggleButton Example public class MainActivity extends Activity { private ToggleButton togglebutton1, togglebutton2; private Button buttonsubmit; protected void oncreate(bundle savedinstancestate) {
igap Technologies 2 addlisteneronbuttonclick(); public void addlisteneronbuttonclick(){ //Getting the ToggleButton and Button instance from the layout xml file togglebutton1=(togglebutton)findviewbyid(r.id.togglebutton1); togglebutton2=(togglebutton)findviewbyid(r.id.togglebutton2); buttonsubmit=(button)findviewbyid(r.id.button1); //Performing action on button click buttonsubmit.setonclicklistener(new OnClickListener(){ public void onclick(view view) { StringBuilder result = new StringBuilder(); result.append("togglebutton1 : ").append(togglebutton1.gettext()); result.append("\ntogglebutton2 : ").append(togglebutton2.gettext()); //Displaying the message in toast Toast.makeText(getApplicationContext(), result.tostring(),toast.length_long). show(); ); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android CheckBox Example public class MainActivity extends Activity { CheckBox pizza,coffe,burger; Button buttonorder;
igap Technologies 3 protected void oncreate(bundle savedinstancestate) { addlisteneronbuttonclick(); public void addlisteneronbuttonclick(){ //Getting instance of CheckBoxes and Button from the activty_main.xml file pizza=(checkbox)findviewbyid(r.id.checkbox1); coffe=(checkbox)findviewbyid(r.id.checkbox2); burger=(checkbox)findviewbyid(r.id.checkbox3); buttonorder=(button)findviewbyid(r.id.button1); //Applying the Listener on the Button click buttonorder.setonclicklistener(new OnClickListener(){ public void onclick(view view) { int totalamount=0; StringBuilder result=new StringBuilder(); result.append("selected Items:"); if(pizza.ischecked()){ result.append("\npizza 100Rs"); totalamount+=100; if(coffe.ischecked()){ result.append("\ncoffe 50Rs"); totalamount+=50; if(burger.ischecked()){ result.append("\nburger 120Rs"); totalamount+=120; result.append("\ntotal: "+totalamount+"rs"); //Displaying the message on the toast Toast.makeText(getApplicationContext(), result.tostring(), Toast.LENGTH_LONG).sh ow(); );
igap Technologies 4 public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android AlertDialog Example public class MainActivity extends Activity { protected void oncreate(bundle savedinstancestate) { AlertDialog.Builder builder = new AlertDialog.Builder(this); //Uncomment the below code to Set the message and title from the strings.xml file //builder.setmessage(r.string.dialog_message).settitle(r.string.dialog_title); //Setting message manually and performing action on button click builder.setmessage("do you want to close this application?").setcancelable(false).setpositivebutton("yes", new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int id) { finish(); ).setnegativebutton("no", new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int id) { // Action for 'NO' Button dialog.cancel(); ); //Creating dialog box AlertDialog alert = builder.create();
igap Technologies 5 //Setting the title manually alert.settitle("alertdialogexample"); alert.show(); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; next prev Android Spinner Example public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener { String[] country = { "India", "USA", "China", "Japan", "Other", ; protected void oncreate(bundle savedinstancestate) { //Getting the instance of Spinner and applying OnItemSelectedListener on it Spinner spin = (Spinner) findviewbyid(r.id.spinner1); spin.setonitemselectedlistener(this); try); //Creating the ArrayAdapter instance having the country list ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,coun aa.setdropdownviewresource(android.r.layout.simple_spinner_dropdown_item); //Setting the ArrayAdapter data on the Spinner spin.setadapter(aa);
igap Technologies 6 //Performing action onitemselected and onnothing selected public void onitemselected(adapterview<?> arg0, View arg1, int position,long id) { Toast.makeText(getApplicationContext(),country[position],Toast.LENGTH_LONG).sho w(); public void onnothingselected(adapterview<?> arg0) { // TODO Auto-generated method stub public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android ListView File: activity_main.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="listview.example.com.listview.mainactivity"> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="fill_parent"
igap Technologies 7 /> </android.support.constraint.constraintlayout> mylist.xml File: mylist.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="medium Text" android:textstyle="bold" android:textappearance="?android:attr/textappearancemedium" android:layout_marginleft="10dp" android:layout_margintop="5dp" android:padding="2dp" android:textcolor="#4d4d4d" /> File:strings.xml <resources> <string name="app_name">listview</string> <string-array name="array_technology"> <item>android</item> <item>java</item> <item>php</item> <item>hadoop</item> <item>sap</item> <item>python</item> <item>ajax</item> <item>c++</item> <item>ruby</item> <item>rails</item> <item>.net</item> <item>perl</item> </string-array> </resources>
igap Technologies 8 File: MainActivity.java package listview.example.com.listview; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.listview; import android.widget.textview; import android.widget.toast; public class MainActivity extends AppCompatActivity { ListView listview; TextView textview; String[] listitem; protected void oncreate(bundle savedinstancestate) { listview=(listview)findviewbyid(r.id.listview); textview=(textview)findviewbyid(r.id.textview); listitem = getresources().getstringarray(r.array.array_technology); final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.r.layout.simple_list_item_1, android.r.id.text1, listitem); listview.setadapter(adapter); listview.setonitemclicklistener(new AdapterView.OnItemClickListener() { public void onitemclick(adapterview<?> adapterview, View view, int position, lon g l) { // TODO Auto-generated method stub String value=adapter.getitem(position); Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show(); );
igap Technologies 9 Android RatingBar Example public class MainActivity extends Activity { RatingBar ratingbar1; Button button; protected void oncreate(bundle savedinstancestate) { addlisteneronbuttonclick(); public void addlisteneronbuttonclick(){ ratingbar1=(ratingbar)findviewbyid(r.id.ratingbar1); button=(button)findviewbyid(r.id.button1); //Performing action on Button Click button.setonclicklistener(new OnClickListener(){ public void onclick(view arg0) { //Getting the rating and displaying it on the toast String rating=string.valueof(ratingbar1.getrating()); Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show(); ); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android SeekBar Example
igap Technologies 10 public class MainActivity extends Activity implements OnSeekBarChangeListener{ SeekBar seekbar1; protected void oncreate(bundle savedinstancestate) { seekbar1=(seekbar)findviewbyid(r.id.seekbar1); seekbar1.setonseekbarchangelistener(this); public void onprogresschanged(seekbar seekbar, int progress, boolean fromuser) { Toast.makeText(getApplicationContext(),"seekbar progress: "+progress, Toast.LENGT H_SHORT).show(); public void onstarttrackingtouch(seekbar seekbar) { Toast.makeText(getApplicationContext(),"seekbar touch started!", Toast.LENGTH_SHO RT).show(); public void onstoptrackingtouch(seekbar seekbar) { Toast.makeText(getApplicationContext(),"seekbar touch stopped!", Toast.LENGTH_SH ORT).show(); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Android DatePicker Example public class MainActivity extends Activity { DatePicker picker;
igap Technologies 11 Button displaydate; TextView textview1; protected void oncreate(bundle savedinstancestate) { textview1=(textview)findviewbyid(r.id.textview1); picker=(datepicker)findviewbyid(r.id.datepicker1); displaydate=(button)findviewbyid(r.id.button1); textview1.settext(getcurrentdate()); displaydate.setonclicklistener(new OnClickListener(){ public void onclick(view view) { textview1.settext(getcurrentdate()); ); public String getcurrentdate(){ StringBuilder builder=new StringBuilder(); builder.append("current Date: "); builder.append((picker.getmonth() + 1)+"/");//month is 0 based builder.append(picker.getdayofmonth()+"/"); builder.append(picker.getyear()); return builder.tostring(); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android TimePicker Example
igap Technologies 12 public class MainActivity extends Activity { TextView textview1; TimePicker timepicker1; Button changetime; protected void oncreate(bundle savedinstancestate) { textview1=(textview)findviewbyid(r.id.textview1); timepicker1=(timepicker)findviewbyid(r.id.timepicker1); //Uncomment the below line of code for 24 hour view timepicker1.setis24hourview(true); changetime=(button)findviewbyid(r.id.button1); textview1.settext(getcurrenttime()); changetime.setonclicklistener(new OnClickListener(){ public void onclick(view view) { textview1.settext(getcurrenttime()); ); public String getcurrenttime(){ String currenttime="current Time: "+timepicker1.getcurrenthour()+":"+timepicker1. getcurrentminute(); return currenttime; public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true;
igap Technologies 13 Android Image Slider File: activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_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="com.example.test.imageslider.mainactivity"> <android.support.v4.view.viewpager android:id="@+id/viewpage" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout> File: MainActivity.java package com.example.test.imageslider; import android.support.v4.view.viewpager; import android.support.v7.app.appcompatactivity; import android.os.bundle; public class MainActivity extends AppCompatActivity { protected void oncreate(bundle savedinstancestate) { ViewPager mviewpager = (ViewPager) findviewbyid(r.id.viewpage); ImageAdapter adapterview = new ImageAdapter(this); mviewpager.setadapter(adapterview);
igap Technologies 14 ImageAdapter class Now create ImageAdapter class which extends PagerAdapter for android image slider. Place some images in drawable folder which are to be slid. File: ImageAdapter.java package com.example.test.imageslider; import android.content.context; import android.support.v4.view.pageradapter; import android.support.v4.view.viewpager; import android.view.view; import android.view.viewgroup; import android.widget.imageview; public class ImageAdapter extends PagerAdapter{ Context mcontext; ImageAdapter(Context context) { this.mcontext = context; public boolean isviewfromobject(view view, Object object) { return view == ((ImageView) object); private int[] sliderimageid = new int[]{ R.drawable.image1, R.drawable.image2, R.drawable.image3,R.drawable.image4, R. drawable.image5, ; public Object instantiateitem(viewgroup container, int position) { ImageView imageview = new ImageView(mContext); imageview.setscaletype(imageview.scaletype.center_crop); imageview.setimageresource(sliderimageid[position]);
igap Technologies 15 ((ViewPager) container).addview(imageview, 0); return imageview; public void destroyitem(viewgroup container, int position, Object object) { ((ViewPager) container).removeview((imageview) object); public int getcount() { return sliderimageid.length; Android Share App Data (ACTION_SEND) public class MainActivity extends AppCompatActivity { Button sharebutton; protected void oncreate(bundle savedinstancestate) { sharebutton=(button)findviewbyid(r.id.button); sharebutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { Intent shareintent = new Intent(android.content.Intent.ACTION_SEND); shareintent.settype("text/plain"); shareintent.putextra(intent.extra_subject,"insert Subject here"); String app_url = " https://play.google.com/store/apps/details?id=my.example.ja vatpoint"; shareintent.putextra(android.content.intent.extra_text,app_url); startactivity(intent.createchooser(shareintent, "Share via")); );
igap Technologies 16 Android Option Menu Example menu_main.xml It contains three items as show below. It is created automatically inside the res/menu directory. File: menu_main.xml <menu xmlns:androclass="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item1" android:title="item 1"/> <item android:id="@+id/item2" android:title="item 2"/> <item android:id="@+id/item3" android:title="item 3"/> </menu> File: MainActivity.java package com.javatpoint.optionmenu; import android.os.bundle; import android.app.activity; import android.view.menu; import android.view.menuitem; import android.widget.toast; public class MainActivity extends Activity { protected void oncreate(bundle savedinstancestate) { public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu);//menu Resource, Menu return true; public boolean onoptionsitemselected(menuitem item) { show(); switch (item.getitemid()) { case R.id.item1: Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).
igap Technologies 17 return true; case R.id.item2: Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show(); return true; case R.id.item3: Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show(); return true; default: return super.onoptionsitemselected(item); Android Context Menu Example File: MainActivity.java package com.javatpoint.contextmenu; import android.os.bundle; import android.app.activity; import android.view.contextmenu; import android.view.contextmenu.contextmenuinfo; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.listview; import android.widget.toast; public class MainActivity extends Activity { ListView listview1; String contacts[]={"ajay","sachin","sumit","tarun","yogesh"; protected void oncreate(bundle savedinstancestate) {
igap Technologies 18 listview1=(listview)findviewbyid(r.id.listview1); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.sim ple_list_item_1,contacts); listview1.setadapter(adapter); // Register the ListView for Context menu registerforcontextmenu(listview1); public void oncreatecontextmenu(contextmenu menu, View v, ContextMenuInfo menuin fo) { super.oncreatecontextmenu(menu, v, menuinfo); menu.setheadertitle("select The Action"); menu.add(0, v.getid(), 0, "Call");//groupId, itemid, order, title menu.add(0, v.getid(), 0, "SMS"); public boolean oncontextitemselected(menuitem item){ if(item.gettitle()=="call"){ Toast.makeText(getApplicationContext(),"calling code",toast.length_long).sho w(); else if(item.gettitle()=="sms"){ Toast.makeText(getApplicationContext(),"sending sms code",toast.length_lon G).show(); else{ return false; return true;
igap Technologies 19 Android Internal Storage Example Activity class Let's write the code to write and read data from the internal storage. File: MainActivity.java package com.example.internalstorage; import java.io.bufferedreader; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstreamreader; import android.os.bundle; import android.app.activity; import android.content.context; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.toast; public class MainActivity extends Activity { EditText edittextfilename,edittextdata;
igap Technologies 20 Button savebutton,readbutton; protected void oncreate(bundle savedinstancestate) { edittextfilename=(edittext)findviewbyid(r.id.edittext1); edittextdata=(edittext)findviewbyid(r.id.edittext2); savebutton=(button)findviewbyid(r.id.button1); readbutton=(button)findviewbyid(r.id.button2); //Performing Action on Read Button savebutton.setonclicklistener(new OnClickListener(){ public void onclick(view arg0) { String filename=edittextfilename.gettext().tostring(); String data=edittextdata.gettext().tostring(); FileOutputStream fos; try { fos = openfileoutput(filename, Context.MODE_PRIVATE); //default mode is PRIVATE, can be APPEND etc. fos.write(data.getbytes()); fos.close(); Toast.makeText(getApplicationContext(),filename + " saved", Toast.LENGTH_LONG).show(); catch (FileNotFoundException e) {e.printstacktrace(); catch (IOException e) {e.printstacktrace(); ); //Performing Action on Read Button readbutton.setonclicklistener(new OnClickListener(){
igap Technologies 21 Reader public void onclick(view arg0) { String filename=edittextfilename.gettext().tostring(); StringBuffer stringbuffer = new StringBuffer(); try { //Attaching BufferedReader to the FileInputStream by the help of InputStream BufferedReader inputreader = new BufferedReader(new InputStreamReader( openfileinput(filename))); String inputstring; //Reading data line by line and storing it into the stringbuffer while ((inputstring = inputreader.readline())!= null) { stringbuffer.append(inputstring + "\n"); catch (IOException e) { e.printstacktrace(); //Displaying data on the toast Toast.makeText(getApplicationContext(),stringBuffer.toString(), Toast.LENGTH_LONG).show(); ); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android External Storage Example You need to provide the WRITE_EXTERNAL_STORAGE permission.
igap Technologies 22 <uses-permission android:name="android.permission.write_external_storage"/> File: Activity_Manifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.externalstorage" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="16" /> <uses-permission android:name="android.permission.write_external_storage"/> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.example.externalstorage.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> File: MainActivity.java package com.example.externalstorage; import java.io.bufferedreader; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream;
igap Technologies 23 import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstreamwriter; import android.os.bundle; import android.app.activity; import android.content.context; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.toast; public class MainActivity extends Activity { EditText edittextfilename,edittextdata; Button savebutton,readbutton; protected void oncreate(bundle savedinstancestate) { edittextfilename=(edittext)findviewbyid(r.id.edittext1); edittextdata=(edittext)findviewbyid(r.id.edittext2); savebutton=(button)findviewbyid(r.id.button1); readbutton=(button)findviewbyid(r.id.button2); //Performing action on save button savebutton.setonclicklistener(new OnClickListener(){ public void onclick(view arg0) { String filename=edittextfilename.gettext().tostring(); String data=edittextdata.gettext().tostring(); FileOutputStream fos; try { File myfile = new File("/sdcard/"+filename); myfile.createnewfile(); FileOutputStream fout = new
igap Technologies 24 FileOutputStream(myFile); OutputStreamWriter myoutwriter = new OutputStreamWriter(fOut); myoutwriter.append(data); myoutwriter.close(); fout.close(); Toast.makeText(getApplicationContext(),filename + " saved",toast.length_long).show(); catch (FileNotFoundException e) {e.printstacktrace(); catch (IOException e) {e.printstacktrace(); ); //Performing action on Read Button readbutton.setonclicklistener(new OnClickListener(){ public void onclick(view arg0) { String filename=edittextfilename.gettext().tostring(); StringBuffer stringbuffer = new StringBuffer(); String adatarow = ""; String abuffer = ""; try { File myfile = new File("/sdcard/"+filename); FileInputStream fin = new FileInputStream(myFile); BufferedReader myreader = new BufferedReader( new InputStreamReader(fIn)); while ((adatarow = myreader.readline())!= null) { abuffer += adatarow + "\n"; myreader.close();
igap Technologies 25 catch (IOException e) { e.printstacktrace(); Toast.makeText(getApplicationContext (),abuffer,toast.length_long).show(); ); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android SQLite DatabaseClass public class DatabaseClass extends SQLiteOpenHelper { public static String urlloginverification = "http://bankbot-001- site1.mysitepanel.net/a_login.php"; public static String urlaskquestion = "http://bankbot-001- site1.mysitepanel.net/a_askquestion.php"; public static String urlwebaddress = "http://bankbot-001- site1.mysitepanel.net/"; public static SQLiteDatabase database; public DatabaseClass(Context context){ super(context, "BankBot", null, 1); public void oncreate(sqlitedatabase arg) { // TODO Auto-generated method stub public void onupgrade(sqlitedatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub public static void execnonquery(string query){ //Execute Insert, Update, Delete, Create table queries database.execsql(query);
igap Technologies 26 public static Cursor getcursordata(string query){ Cursor res = database.rawquery(query, null); return res; public static String getsinglevalue(string query) { try { Cursor res = getcursordata(query); String value = ""; if (res.movetonext()) { return res.getstring(0); return value; catch (Exception ex) { return ""; public static int getnoofrows(string query){ Cursor res = database.rawquery(query, null ); return res.getcount(); public static boolean checkifrecordexist(string query){ Cursor res = database.rawquery(query, null ); if(res.getcount() > 0) return true; else return false; Android Media Player Example public class MainActivity extends Activity { Button start,pause,stop; protected void oncreate(bundle savedinstancestate) { start=(button)findviewbyid(r.id.button1); pause=(button)findviewbyid(r.id.button2); stop=(button)findviewbyid(r.id.button3); //creating media player final MediaPlayer mp=new MediaPlayer(); try{ //you can change the path, here path is external directory(e.g. sdcard) /Music/m aine.mp3
igap Technologies 27 ne.mp3"); mp.setdatasource(environment.getexternalstoragedirectory().getpath()+"/music/mai mp.prepare(); catch(exception e){e.printstacktrace(); start.setonclicklistener(new OnClickListener() { public void onclick(view v) { mp.start(); ); pause.setonclicklistener(new OnClickListener() { public void onclick(view v) { mp.pause(); ); stop.setonclicklistener(new OnClickListener() { public void onclick(view v) { mp.stop(); );
igap Technologies 28 Android Video Player Example public class MainActivity extends Activity { protected void oncreate(bundle savedinstancestate) { VideoView videoview =(VideoView)findViewById(R.id.videoView1); //Creating MediaController MediaController mediacontroller= new MediaController(this); mediacontroller.setanchorview(videoview); mp4"); //specify the location of media file Uri uri=uri.parse(environment.getexternalstoragedirectory().getpath()+"/media/1. //Setting MediaController and URI, then starting the videoview videoview.setmediacontroller(mediacontroller); videoview.setvideouri(uri); videoview.requestfocus(); videoview.start(); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; Android MediaRecorder Example
igap Technologies 29 public class MainActivity extends Activity { MediaRecorder recorder; File audiofile = null; static final String TAG = "MediaRecording"; Button startbutton,stopbutton; public void oncreate(bundle savedinstancestate) { startbutton = (Button) findviewbyid(r.id.button1); stopbutton = (Button) findviewbyid(r.id.button2); public void startrecording(view view) throws IOException { startbutton.setenabled(false); stopbutton.setenabled(true); //Creating file File dir = Environment.getExternalStorageDirectory(); try { audiofile = File.createTempFile("sound", ".3gp", dir); catch (IOException e) { Log.e(TAG, "external storage access error"); return; //Creating MediaRecorder and specifying audio source, output format, encoder & ou tput format recorder = new MediaRecorder(); recorder.setaudiosource(mediarecorder.audiosource.mic); recorder.setoutputformat(mediarecorder.outputformat.three_gpp); recorder.setaudioencoder(mediarecorder.audioencoder.amr_nb); recorder.setoutputfile(audiofile.getabsolutepath()); recorder.prepare(); recorder.start(); public void stoprecording(view view) { startbutton.setenabled(true); stopbutton.setenabled(false); //stopping recorder
igap Technologies 30 recorder.stop(); recorder.release(); //after stopping the recorder, create the sound file and add it to media library. addrecordingtomedialibrary(); protected void addrecordingtomedialibrary() { //creating content values of size 4 ContentValues values = new ContentValues(4); long current = System.currentTimeMillis(); values.put(mediastore.audio.media.title, "audio" + audiofile.getname()); values.put(mediastore.audio.media.date_added, (int) (current / 1000)); values.put(mediastore.audio.media.mime_type, "audio/3gpp"); values.put(mediastore.audio.media.data, audiofile.getabsolutepath()); //creating content resolver and storing it in the external content uri ContentResolver contentresolver = getcontentresolver(); Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri newuri = contentresolver.insert(base, values); //sending broadcast message to scan the media file so that it can be available sendbroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newuri)); Toast.makeText(this, "Added File " + newuri, Toast.LENGTH_LONG).show();
igap Technologies 31 Android TextToSpeech Tutorial public class MainActivity extends Activity implements TextToSpeech.OnInitListener { /** Called when the activity is first created. */ private TextToSpeech tts; private Button buttonspeak; private EditText edittext; public void oncreate(bundle savedinstancestate) { tts = new TextToSpeech(this, this); buttonspeak = (Button) findviewbyid(r.id.button1); edittext = (EditText) findviewbyid(r.id.edittext1); buttonspeak.setonclicklistener(new View.OnClickListener() { public void onclick(view arg0) { speakout(); ); public void ondestroy() { // Don't forget to shutdown tts! if (tts!= null) { tts.stop(); tts.shutdown(); super.ondestroy(); public void oninit(int status) {
igap Technologies 32 if (status == TextToSpeech.SUCCESS) { int result = tts.setlanguage(locale.us); if (result == TextToSpeech.LANG_MISSING_DATA result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "This Language is not supported"); else { buttonspeak.setenabled(true); speakout(); else { Log.e("TTS", "Initilization Failed!"); private void speakout() { String text = edittext.gettext().tostring(); tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; How to make a phone call in android <uses-permission android:name="android.permission.call_phone" />
igap Technologies 33 Intent callintent = new Intent(Intent.ACTION_CALL); callintent.setdata(uri.parse("tel:"+8802177690));//change the number startactivity(callintent); How to send sms in android <uses-permission android:name="android.permission.send_sms"/> //Getting intent and PendingIntent instance Intent intent=new Intent(getApplicationContext(),MainActivity.class); PendingIntent pi=pendingintent.getactivity(getapplicationcontext(), 0, intent,0); //Get the SmsManager instance and call the sendtextmessage method to send message SmsManager sms=smsmanager.getdefault(); sms.sendtextmessage("8802177690", null, "hello javatpoint", pi,null); Android Camera Tutorial File: activity_main.xml <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_centerhorizontal="true" android:text="take a Photo" > </Button> <ImageView android:id="@+id/imageview1" android:layout_width="fill_parent"
igap Technologies 34 android:layout_height="fill_parent" android:layout_above="@+id/button1" android:layout_alignparenttop="true" android:src="@drawable/ic_launcher" > </ImageView> </RelativeLayout> public class MainActivity extends Activity { private static final int CAMERA_REQUEST = 1888; ImageView imageview; public void oncreate(bundle savedinstancestate) { imageview = (ImageView) this.findviewbyid(r.id.imageview1); Button photobutton = (Button) this.findviewbyid(r.id.button1); photobutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { Intent cameraintent = new Intent(android.provider.MediaStore.ACTION_I MAGE_CAPTURE); startactivityforresult(cameraintent, CAMERA_REQUEST); ); protected void onactivityresult(int requestcode, int resultcode, Intent data) { if (requestcode == CAMERA_REQUEST) { Bitmap photo = (Bitmap) data.getextras().get("data"); imageview.setimagebitmap(photo); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu);
igap Technologies 35 return true; Android Service Example Let's see the example of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service. package com.example.serviceexampleaudio; import android.app.service; import android.content.intent; import android.media.mediaplayer; import android.os.ibinder; import android.widget.toast; public class MyService extends Service { MediaPlayer myplayer; public IBinder onbind(intent intent) { return null; public void oncreate() { Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show(); myplayer = MediaPlayer.create(this, R.raw.sun); myplayer.setlooping(false); // Set looping public void onstart(intent intent, int startid) { Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); myplayer.start(); public void ondestroy() { Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
igap Technologies 36 myplayer.stop(); File: MainActivity.java package com.example.serviceexampleaudio; 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; public class MainActivity extends Activity implements OnClickListener { Button buttonstart, buttonstop,buttonnext; public void oncreate(bundle savedinstancestate) { buttonstart = (Button) findviewbyid(r.id.buttonstart); buttonstop = (Button) findviewbyid(r.id.buttonstop); buttonnext = (Button) findviewbyid(r.id.buttonnext); buttonstart.setonclicklistener(this); buttonstop.setonclicklistener(this); buttonnext.setonclicklistener(this); public void onclick(view src) { switch (src.getid()) { case R.id.buttonStart: startservice(new Intent(this, MyService.class)); break; case R.id.buttonStop: stopservice(new Intent(this, MyService.class)); break; case R.id.buttonNext: Intent intent=new Intent(this,NextPage.class); startactivity(intent); break;
igap Technologies 37 Declare the Service in the AndroidManifest.xml file Finally, declare the service in the manifest file. File: AndroidManifest.xml Let's see the complete AndroidManifest.xml file <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:androclass="http://schemas.android.com/apk/res/android" package="com.example.serviceexampleaudio" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.example.serviceexampleaudio.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <service android:name=".myservice" android:enabled="true" /> <activity android:name=".nextpage"/> </application>
igap Technologies 38 </manifest>