[GUIDE] How To Make An Android App

Search This thread

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►
Introduction

Hello and Welcome to android app development guide. In this [guide] i will teachyou how to develop applications for the android platform using java and some simple tools. I will also teach you to add audio/video to your apps and also teach how to make them location aware by adding gps function to it :) :D :D

What You Should Know

Here I am just letting you all Know the pre-requisites of making an app. But then if you dont match the pre-requisites..... its OKAY !! I started it without this xD


  • Some Experience Of Object Oriented Programming
  • Some Experience of JAVA
  • Experience of Using ECLIPSE
  • Have An ANDROID phone so that you know the capabilities of Android


 
Last edited:

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►
Overview

Android Architecture


  • Runs on Linux 2.6
  • Dalvik Virtual Machine, Which Is optimised for mobiles
  • Integrated Browser, based On Webkit Engine
  • Optimized Graphics with Open GL ES
  • SQLite Database for Data storage
Android Application Fundamentals

  • Applications are written in JAVA programming Language
  • Compiled Into Android Package file (.apk)
  • Each Application runs in its own sandbox and linux processes
  • Applications consists of Components, Resources and a Manifest file
Components:

  • Activities
    • Single Screen with a UI [a screen seen by a user, it is an activity. basically a single screen, seen by the user IS an ACTIVITY ]
    • Multiple Activities are required to make a user friendly application ;)
    • When a new activity starts, old activity is pushed on to the Back Stack [ it becomes handy and fast if you press the back button on the phone. the activity on the back stack is not needed to be loaded again ! ]
    • UI can be built with either by XML ( recommended) or in Java ( I hate doing that :p )
    • You can manipulate the lifetime of the activities by certain call back methods. such as onStart[], onPause[], etc.
  • Services

    • They perform long-running operations in the background.
    • Doesn't contain ANY user interface
    • Useful for network operations, playing music, etc.
    • Runs independently of the component that created it ! --> [ say a service that launches a Service is closed. the service is still running ]
    • They can be bound to other application components. [ IF allowed ]
  • Content Providers
    • Used to store and retrieve data and make it accessible to any application.
    • Since, there is no way to share data across the applications, it is the only way !
    • Exposes a public URI that identifies the data set with some unique method or codes.
    • The data is exposed by a simple table on a database model concept.
    • Android contains many providers for things like contacts, media, etc.
  • Broadcast Recievers
    • A component that responds to system-wide broadcast announcement.
    • For Example, if the battery is low, Android Sends a system-wide broadcast, and the application that is listening to it, is responded by a Broadcast Reciever.
    • Applications can also initiate a broadcast that different applications can respond to ! example --> if an application, app1, is dependent on another application, app2, it can start a broadcast for app2. if the app2 exists, it can proceed else it will pop up a message like --- "app2 doesn't exist. plz download it from the market"
    • They, like services, contain no UI
    • Can be used to create Status Bar Notifications
  • Android Manifest File
    • All applications MUST have an AndroidManifest.xml in its root directory.
    • Presents the information about the application to the Android System.
    • Declares the Components used in the application
    • Also Declares the permissions required from the user to run the application.
    • Declares the Minimum Android API level to run that application. [ eg: GingerBread, HoneyComb, IceCreamSandwich, etc. ]



Details About Some Folders
Have You ever Decompiled any apk file ?? If not, do it, cuz it is really important part of app making. since there are many relative things to this.
In here I will
Explain about some folders you get to see in a folder named "res" when you decompile.

  • layout
    In This Folder, You will find some xmls, which looks more like a web page source :p
    And Gibberish until you take a CLOSE LOOK !
    It actually stores in the Layout of your activity. You will get to be familiar with this as we are going to use this :D
  • drawable
    In this folder, You will get the things that makes the app look beautiful !
    Ha! This contains "pngs" that are used in themes. We Will come to this as time passes
  • xml
    In here, Again, XMLs with someting Gibberish till you get a closer Look ! These xmls store your preference activities.
  • anim
    This folder, again xmls, which seem more unreadable. This folder, as the name says, it stores the anim files that has instructions for your animations that you (will) use in the app.
  • values
    This folder, again xmls, which seem even more unreadable. This folder, stores the values for different stuff, like ids, integers color hex's, etc (we will get to this later) .
  • colors
    This folder, again xmls, as the name says, stores the colors that you (will be) using in the app (we will get to this later) .
 
Last edited:

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►
Activities And Explicit Intents

Activities & Explicit Intents

As I've already told you that Activities are one of the primary building blocks of your app. here, we will learn how to create actiities, declare them in AndroidManifest.xml and We will also learn How to go to another activity from one activity. Okay. So now open up Eclipse. and sart a new Android Project.

  • Click on File >> New >> Android Project
    LFZaf5w.png


  • Fill in the details as you wish.... and click finish. :)
    5xqJl84.png

  • After you make a Project. You will get A full working Hello world Application. now, modify the MainActivity.xml in the graphical part like this
    oQMSpKf.png

  • make a new xml file by clicking
    z6nUn8C.png
    . Give a file name like... SecondActivity.xml or something you like Note: This Will be your Second Activity. and now click Finish
  • Now drag the " TextView " from the " form widgets" tab from the left side panel to the graphical editor of your second activity.

Now, Basically what i want to teach is Explicit Intents. Now what we want our app to do is the text written in the MainActivity should be shown to the user when he clicks the "go to second activity" button. So to do this, we need to declare and do something with JAVA !


  • navigate to the .java files -->

    quGL9ze.png

  • Double click the java file and you will et something like this ( gibberish... if you dont like java like me :p )
    vUirRq7.png

    hduDb3O.png


    since we need to define the "EditText" field and the "Button" from the first activity !

    Now, find this

    Code:
    setContentView(R.layout.main);


    after that start typing

    final EditText et = findView

    now press ctrl+space (windows)
    it will show you a list of commands. choose findViewById(id)
    now it will automatically place you along the (id). now start typing ---> R.id.
    and press ctrl+space (windows).
    chose the EditText Value..... Now as you see, it will show an error there. press ctrl+1 to show quick fixes. Add a cast to EditText. Final text will be Like this

    Code:
    final EditText et = (EditText) findViewById(R.id.editText1);


    Now do the same with the "Button"


    Code:
    Button b = (Button) findViewById(R.id.button1);

    Now that you have defined the button. Now you will have to set an OnClickListener for that button. so the it allows User to go to the second activity.

    now start typing

    b.setOnclick... press ctrl+space and choose onClickListener. It will automatically place you in the "()" type there --> new OnClickListener press ctrl+space. you will get something like this

    fTtEQFN.png


    you will get an error. so go to the place ( marked red in the pic and put a semi-colon )

    now, in the following method,

    Code:
    public void onClick(View arg0) {
    				// TODO Auto-generated method stub
    				
    				
    			}

    start typing the following

    Code:
    Intent intent = newInt

    press ctrl+space and choose this


    kl6CA4N.png


    It will automatically place you in packageContext.

    NOTE:

    packageContext == "The java file that is creating the Intent";
    cls == " The java file to whom the Intent Should be passed";



    so, edit it this way

    Code:
    Intent intent = new Intent(MainActivity.this, SecondActivity.class);

    NOTE:

    MainActivity == "The java file that you are editing";
    SecondActivity == " The java file That WILL represent the the SecondActivity.xml";



    It will give you an error. press ctrl+1 and select--> create class "SecondActivity"
    Fill in the details of the new java file and click finish. Now go back to previous java file.

    Now, you have created an intent. But its not defined that what will that intent do !
    So, now, Lets define that ;)

    start typing--> intent.putExtra and press ctrl+space. choose this.

    Q11uLpc.png


    now, you will be automatically placed in the "key". now for the key, you will have to type a string. i would like to call it "thetext". Now, Make sure you type the string WITHIN THE DOUBLE QUOTES..

    For the value, you will have to give the reference of the "EditText" Field. here, i have given it as "et", i will type it this way.

    intent.putExtra("thetext", et.getText().toString());

    Now, you have successfully DEFINED what the intent does. but if you check the coding..... you will notice that the intent is never initialised ! now, to initialise it, type in this -->
    startActivity(intent);
the final MainActivity.java should look like this.

TIJRky9.png





Now, its almost done..... BUT.... ! what the hell is the use of the secondActivity.java o_O ! ?
It is to be edited. only then the text written in the first activity by the user will be shown in the second activity. to do that, go to second activity. Now,



EASY PART

  • Find this in the first java file:
    vUirRq7.png

    hduDb3O.png
  • Copy all that stuff to the SecondActivity.java
  • Change the blue highlited text ( in eclipse ) to the name of the second xml file. (just dont add the extension)


Hard PART

Now, you gotta define the "TextView" on the SecondActivity.xml Since you have given the reference to the SecondActivity.xml by copying all that stuff.

so, start typing,

Code:
TextView tv = findView


NOTE: Here "tv" is the name you have assigned to the "TextView". You can change it if you want. BUT makesure you do the cahnges accordingly in the next steps.

hit ctrl + space. choose >> findViewById(id);

now again, as we already did that before, in the place of "id" just type in "R.id." hit ctrl+space and chose the "TextView"

Now, that You have defined it here, dosent mean that It will give you desired output....
You just have created an intent and have defined it and initialised it in the last java file.
But there is no-one to recieve that intent ! so, start typing the following:

JURMrFy.png


And, in place of text, start typing "getI" and press ctrl+space. put a fullstop, type "getE" hit ctrl+space, put a fullstop again, start typing "getS", ctrl+space again now in the "()" put the string that you have defined in the last java file. since I have defined it as "thetext" i will type that in the "()" like this:

Code:
tv.setText(getIntent().getExtras().getString("thetext"));



Now, its done..... BUT.... ! .... AndroidManifest.xml
you didnt touch it till now. we have to register every activity there. or else, the app will cause a FC error. (Force Closes)


Now, open up the Androidmanifest.xml

UMHSKeK.png


go to the text editor :

IbktDuE.png



and in the end before--> "</application>" add this
Code:
<activity
            android:name="com.blksyn.explicitintents.SecondActivity">
</activity>




Now, its done. Lets start the emulator and Check this if it works !

  • Go to AVD Manager like this:
    D8aW8RF.png
  • Start the AVD emulator.
  • click on run: and click on run again xD. Click on okay.
    eNiT4s1.png

Bingo ! you have created an app which declares Explicit Intents and added a function to activities to catch that intent !

CavNt7h.png
kLQfPLv.png





 
Last edited:

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►
Implicit Intents

Implicit Intents


Now, you must have seen some applications with a "share" button. By clicking on this button, you can share a particular image/video/audio/etc....
What does that application actually do is send a message to other applications to search for the applications capable of handling such type of job. Then it pops up the list of such apps to the user. Now we can also have that list contain our app too !
Here is how.





  • Create a blank project. I gave it the name as "Implicit_intents". But you can choose whatever you want :)
  • Open up the "AndroidManifest.xml" file. (plz dont expect me to show how, cuz i have already shown that earlier and you should know that by now)
    You will see something like this

    001.PNG

  • Copy this from the main activity
    Code:
    	<intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
        	</intent-filter>

    paste it again after the </intent-filter>
    and change it to this

    Code:
    	<intent-filter>
                    <action android:name="android.intent.action.SEND" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <data android:mimeType="image/*" />
        	</intent-filter>


    NOTE:
    Code:
    		<action android:name="android.intent.action.SEND" />

    (self explainatory)
    Code:
     <category android:name="android.intent.category.DEFAULT" />

    This tells the android system waht the category of the intent is. If you dont know what the category really is, you should keep it DEAFAULT.
    Code:
     <data android:mimeType="image/*" />

    This tells the Android system, What type of data can the application "SEND" (* reference to the first one). and "data/*" means that the application can handle any type of imge. Jpeg, png, bmp, etc....

So, this is how your AndroidManifest.xml should look like.

002.PNG



  • Now, go to the xml of your main activity and get rid of that text view. and add an "ImageView" from "Images and media" tab on the left


    003.PNG
  • Now, go to your main java file and give a refernece to that ImageView


    004.PNG


    NOTE: "iv" is just a name given to the ImageView. so, you can change it if you want. But you will have to adapt to it and make changes in the steps accordingly.

    Import the image view thing and add a cast by hitting ctrl+space
  • Now that you have specified the ImageView, you now have to set the ImageView to show the image the user wanna send. so, start typing in "iv.setImage" and press ctrl+space.

    005.png


    Now, since the image is IN the intent sent by the gallery after the user clicks the share button, we have to "get" the "EXTRAS" from the intent. So, start typing in in the "()". "getInt" press ctrl+space put a "." again type "getExt" choose the only option available, put a "." again and type "get" choose the first option. now, for the key, we are gonna use a constant from the INTENT class, that is called "EXTRA_STREAM". So ,just start typing in "Intent", put a ".", type "extra_" and choose "EXTRA_STREAM".


    This "EXTRA_STREAM" is nothing but the "URI" to the image the user wants to send. You will have an error now in the line even after putting a ";" in the end. so press the quick fix combo "ctrl+1" and add a cast to (URI).

    006.PNG



Now, you have successfully built an application that can handle the "share" kind of intent. now if you run this app in the emulator, you will probably have an FC. Since the app does not have any intent to process during the launch, it will FC. but if you go to gallery and click on share, you will get this app in the list. And also, if you click on this app, you will see the image you wanted to share.


So, this ends our chapter of Implicit Intents. You can now use your imaginations and use the combos of the previous and this chapter to build a pretty good basic app ! and the credit will be yours ! But dont forget to thank me for my efforts. haha... and also if i help you in some place.

And last but not the least in this chapter, If you have any questions, post a reply in this thread :) you will surely be answered :D :D :good:

 
Last edited:

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►
Widgets

I am going to teach you how to make a widget.
This widget will go to a specified site !

So , make a new android application in eclipse
name it whatever you like !

  • Click on File >> New >> Android Project
    LFZaf5w.png


  • Fill in the details as you wish.... and click finish. :)
    5xqJl84.png

  • After you make a Project. You will get A full working Hello world Application. Now, modify the activity_main.xml in the graphical part like this
    rqqNJk9.png


    You will get something like this:
    EKQ1W3z.png

  • Now Open Up the AndroidManifest.xml. and remove this part:
    1HeUHQz.png


    And add this part:
    CffSMWe.png


  • make a new xml file by clicking
    z6nUn8C.png
    . and change Resource type from Layout to "AppWidget Provider" and now click Finish

    Note: This Will be your android:resource file. highlighted in the previous image.
  • Now Open up that xml. You will find it in the /res/xml directory. you will get something like this:
    rImGD07.png


    Now click on the "red" underlined part. you will get something like this:
    JuJTdy5.png

Now, Basically we are making a 2x2 widget. You need to specify that somewhere right ? That is the place. but how do you specify ?? It can be calculated using this formula:
Code:
the min width =

[(number_of_cells) * 74] - 2

2x2

min widht = [2*74]-2 = 144
min height = 144 ! :)

so, fill in the details like this:
pxglceH.png



Now, the layout part of the widget is complete. What we want to do is the JAVA thing now. So, open up the MainActivity.java
84nSSuV.png




  • Double click the java file and you will et something like this
    vUirRq7.png

    hduDb3O.png


    since we Are making a widget, We cannot have Much functions in here. Unlike activities(which have loads of functions in it) widget restricts us to very few. So, we are not going to need all the stuff You are seeing in java file. so do one thing. delete all the things. Here is how it shoud look like:
    hu53KCG.png


    Now, Since We are not making a regular activity, We are not going to extend activity. Now we are going to extend the "AppWidgetProvider"


    Code:
    public class MainActivity extends AppWidgetProvider {

    Now "AppWidgetProvider" Does not allow "OnCreate" Methods. what we are allowed is onUpdate Method, Since this is going to be called every single time our widget updates (N/A in this widget, but still you have to write it)
    In that method, start typing

    Code:
    onUpdate

    now press ctrl+space (windows only)

    You will have something like this:
    Code:
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
    		int[] appWidgetIds) {
    	// TODO Auto-generated method stub
    	super.onUpdate(context, appWidgetManager, appWidgetIds);
    	}

    In this class you have to define everything. Now what we are going to do is we will have to define a for loop:
    Code:
    for(int i = 0; i<appWidgetIds.length; i++){
    
    	}

    Now first thing in this for loop, we are gonna have to refer to our current appWidgetID. so,
    Code:
    int ID = appWidgetIds[i];

    Done! now wahat we are goingg to do with this widget ??
    ANS: We are going to launch a web site b opening our browser.

    Okay, so how are we going to do it ??
    Yes, exactly. like we did it before, we are going define an intent, like this:
    Code:
    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("URL_OF_YOUR_WEBSITE"));

    Now, It still isnt going to launch anything. What we have to do, is, set a "PendingIntent".
    A pending intent is actually an intent which gives access to, um, ur app (widget, in this case,). so, start typing in
    Code:
    Pending

    press ctrl+space. name it what you want. then put " = " . again type "PendingIntent." and press ctrl+space and select this:
    Code:
    getActivity(context, requestCode, intent, flags)


    Now, for context, it has olready defined in your context (onUpdate method).

    requestCode = flags 0 (we aren't using them here)
    and for intent, put your intents name like I've put in "in". it will look something like this:
    Code:
    PendingIntent pen =  PendingIntent.getActivity(context, 0, in, 0);

    NOW, SINCE THIS IS A WIDGET AND NOT A SIMPLE, REGULAR ACTIVITY, WE CAN'T USE THE "findViewById(id)" THING HERE, WE HAVE TO USE "RemoteViews" since these views are
    in the widget and not public.
    So, we are going to create new instance of this
    type in,
    Code:
    RemoteViews view = new Re

    and press ctrl+space an choose this:
    Code:
    RemoteViews(packageName, layoutId)

    for package name:
    UIbAR0J.png


    for layoutId:
    Code:
    R.layout.activity_main

    now, after this, like we set onClickListener, We have to set onClickPendingIntent
    like this:
    l7OoIY8.png


    Now, give respective arguments in the brackets. The final thing should look like this:
    Code:
    view.setOnClickPendingIntent(R.id.imageButton1, pen);
    NOW, Last thing. it is to set up an "appWidgetManager"
    so, Start typing:
    JHLNA6T.png

    and give the respective arguments.
    final MainActivity.java should look like this
    R0etqBq.png


    It wil Never launch a browser yet,, think why ???

    We havent yet given up the permissions yet !!!

    So, open up the AndroidManifest.xml
    Go to permissions tab, youll see something like this:
    hdLG87b.png

    click on Add.
    edit like this.
    PyWxqDA.png








  • Now, its done. Lets start the emulator and Check this if it works !

    • Go to AVD Manager like this:
      D8aW8RF.png
    • Start the AVD emulator.
    • click on run: and click on run again xD. Click on okay.
      eNiT4s1.png

    Bingo ! you have created aWidget !!

    gCFEmH7.png
    xHWlv1I.png
    IuzslSQ.png



 
Last edited:

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►
Audio/Video and multimedia

Audio

In this one, i will tell you how to use the "raw" folder to play audio(s) from the folder using MediaPlayer thingy. Okay. So now open up Eclipse. and start a new Android Project.

  • Click on File >> New >> Android Project
    LFZaf5w.png


  • Fill in the details as you wish.... and click finish. :)

  • After you make a Project. You will get A full working Hello world Application. now, modify the MainActivity.xml in the graphical part by adding a button to it and save it.
    yWd8Q1H.png

  • Now, in the project, right click on res folder, new>>folder. name the folder as "raw". THEY ALL SHOULD BE IN SMALLS. NONE OF THE LETTER SHOULD BE IN CAPS
    Mnt6N1N.png

  • Now, have a short mp3 file like the one in attachments, and drag it to the newly created folder.

Now, its all set, what our app will do is it will play that short mp3 file i the "raw" folder as soon as we press that button. Now, for that sake we are going to use MediaPlayer class. Open up the MainActivity.java fir this.


  • navigate to the .java files -->

    quGL9ze.png

  • Double click the java file and you will et something like this ( gibberish... if you dont like java like me :p )
    vUirRq7.png

    hduDb3O.png


    we need to define the field and the "Button" from the first activity !
    NOTE: as we advance in the tutorial, i will assume that you have done it from the start, hence i will not show such small things everytime, to make the tut short, sweet and simple. refer the first tutorial for this step.
    It should look like this:

    Code:
    Button b = (Button) findViewById(R.id.button1);

    Now that you have defined the button. Now you will have to set an OnClickListener for that button. so the it allows User to go to the second activity.

    now start typing

    b.setOnclick... press ctrl+space and choose onClickListener. It will automatically place you in the "()" type there --> new OnClickListener press ctrl+space. you will get something like this

    fTtEQFN.png


    you will get an error. so go to the place ( marked red in the pic and put a semi-colon )

    now, in the following method,

    Code:
    public void onClick(View arg0) {
    				// TODO Auto-generated method stub
    				
    				
    			}

    start typing the following

    Code:
    MediaPlayer mp = MediaPlayer.

    press ctrl+space and choose this


    bJZqUUC.png


    It will automatically place you in "context".

    NOTE:

    context == "The java file that is creating the Intent";
    resid == " The id of the resource (here, id of the mp3 file in the folder"raw")";



    so, edit it this way

    Code:
    MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.beep);

    NOTE:

    MainActivity == "The java file that you are editing";
    R.raw.beep == "Here , the name of the mp3 file in my "raw" folder is beep, it can be according to you";

So, we have just defined the mp class.
BUT, who is invoking it ?
Nobody, we need to invoke it ourselves. here, there is no relation or job to be done by "intent" like we did in earlier tutorials MediaPlayer class is totally different....
We need to do this in order to invoke.

Code:
mp.start();

NOTE:
mp == "the name that i gave to MediaPlayer object";
Code:
MediaPlayer [COLOR="SeaGreen"]mp[/COLOR] = MediaPlayer.create(MainActivity.this, R.raw.beep);
.
Save it and run it on your AVD

Now, its done. Lets start the emulator and Check this if it works !

  • Go to AVD Manager like this:
    D8aW8RF.png
  • Start the AVD emulator.
  • click on run: and click on run again xD. Click on okay.
    eNiT4s1.png

YAY ! it works !! click on that button ;)

maX0BtU.png






Video

In this one, I will tell you how to play video(s) which are already in your sdcard. Okay. So now open up Eclipse. and start a new Android Project.


  • Click on File >> New >> Android Project
    LFZaf5w.png


  • Fill in the details as you wish.... and click finish. :)

  • After you make a Project. You will get A full working Hello world Application. now, modify the MainActivity.xml in the graphical part by adding a button to it and save it.
    yWd8Q1H.png

  • Now, place a video in ur sdcard (wherever you want, will explain later).

    NOTE:
  • Video should be in mp4 format, as android has built-in encoders for that.

Now, its all set, what our app will do is it will play that short mp4 video file in the sdcard as soon as activity is invoked. Now, for that sake we are going to use VideoView class.

Go to res/layout/activity_main.xml
  • Delete the text view and add a VideoView:
    UUEmADC.png

  • Save it

Open up the MainActivity.java like this.

  • navigate to the .java files -->

    quGL9ze.png

  • Double click the java file and you will see something like this ( gibberish... if you dont like java like me :p )
    vUirRq7.png

    hduDb3O.png


    we need to define the VideoView class.
    NOTE: as we advance in the tutorial, i will assume that you have done it from the start, hence i will not show such small things everytime, to make the tut short, sweet and simple. refer the first tutorial for this step.Its just like defining a button
    It should look like this:

    Code:
    VideoView vv = (VideoView) findViewById(R.id.videoView1);

    Now that you have defined the VV. Now you will have to set properties of the VV so that we can play the video and offer controls(rewind, play/pause, fast fwd) and etc.

    now start typing

    vv.setV... press ctrl+space and you will get something like this

    VNBJzVK.png


    choose that, and enter string path:

    Code:
    vv.setVideoPath("/sdcard/path/to/video.mp4");

    note that the /sdcard is a must. it can also be written as /mnt/sdcard/ however. not all phones have this functionability.
    so, its better to write /sdcard.
  • Since we need to have controls while playing the video, we need to instantiate that first, so,
    Code:
    vv.setMediaController(new MediaController(this));

    Disstection:: MediaCOntroller, Name explains itself. since we didnt create the MediaController anywhere, we made a new controller
    and passed in the context as "this"

    -_- "java". lol


    Now that we want to start it as soon as the activity is started.
    we add this:

    Code:
    vv.start();

    we also do not want the backlights to be down while playing the video so,

    Code:
    vv.requestFocus();


Save it and run it on your ACTUAL ANDROID DEVICE.

NOTE: Please do not test this on emulator.[/size]




Images and Camera

In this one, i will tell you how to use the Mediastore and device's camera to get the picture/photo from the camera. Okay. So now open up Eclipse. and start a new Android Project.

  • Click on File >> New >> Android Project
    LFZaf5w.png


  • Fill in the details as you wish.... and click finish. :)

  • After you make a Project. You will get A full working Hello world Application. now, modify the MainActivity.xml in the graphical part by adding a button to it and save it.
    yWd8Q1H.png


Now, its all set, what our app will do is it will click a picture using device's camera, and give you the picture. so, open up your main_activity.xml and delete the TextView. Add a button (which will initiate device's camera) and an ImageView (which will show you the pic that the user will click).

XNfYBYx.png


Then open up your MainActivity.java


  • navigate to the .java files -->

    quGL9ze.png

  • Double click the java file and you will et something like this ( gibberish... if you dont like java like me :p )
    vUirRq7.png

    hduDb3O.png


    we need to define the field and the "Button" from the first activity !
    NOTE: as we advance in the tutorial, i will assume that you have done it from the start, hence i will not show such small things everytime, to make the tut short, sweet and simple. refer the first tutorial for this step.
    It should look like this:

    Code:
    Button b = (Button) findViewById(R.id.button1);

    Now that you have defined the button. Now you will have to set an OnClickListener for that button. so the it allows User to go to the second activity.

    now start typing

    b.setOnclick... press ctrl+space and choose onClickListener. It will automatically place you in the "()" type there --> new OnClickListener press ctrl+space. you will get something like this

    fTtEQFN.png


    you will get an error. so go to the place ( marked red in the pic and put a semi-colon )

    now, in the following method,

    Code:
    public void onClick(View arg0) {
    				// TODO Auto-generated method stub
    				
    				
    			}

    Make an instance on Intent
    Code:
    Intent intent = new Intent();

    now in the arguments, pass in "android.provider.MediaStore.ACTION_IMAGE_CAPTURE"
    this allows us to actually launch the camera app(s) installed on the device. so as to
    get a captured image.

    Till now, we started intents just like starting any activity.
    but in this particular case, we are starting another activity,
    with an expectation of recieving some data back.
    that is, result.
    so, next, start typing "startAct...."
    and choose this
    Code:
    startActivityForResult(intent, requestCode)

    NOTE:

    intent = "The Intent that we already created"; (since I've named it as "intent" , ill pass in
    "intent")
    requstCode == "we will not be using this, so, skip it, pass in a zero";

    Code:
    startActivityForResult(intent, 0);


    now then, we are expecting a result.
    so, we must set a reciever for it, right ?
    lets do that first and then play with the ImageView

    so, after the method, make a new method, start typing
    MsAJck9.png


    Now, we have set the reciever.
    now, we need to give an instance of ImageView.
    so, declaration has to be before the onCreate method.
    and definition can be in both the methods.
    so, declare an ImageView outside the onCreate method
    Code:
    ImageView iv;

    and in the onCreate method,
    Code:
    iv = (ImageView) findViewById(R.id.imageView1);
    and lastly, in the onActivityResult method,
    declare and define a bitmap, which will save the clicked pic.
    Code:
    Bitmap bm = (Bitmap) data.getExtras().get("data");

    now, bm will save the clicked pic in itself.
    and to display it, we use iv. so type in this:
    Code:
    iv.setImageBitmap(bm);

At The End, this is how the MainActivity.java should look like:
Code:
package com.example.camtut;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
ImageView iv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.imageView1);
		Button b = (Button) findViewById(R.id.button1);
		b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
			Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 0);
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		Bitmap bm = (Bitmap) data.getExtras().get("data");
		iv.setImageBitmap(bm);
	}
	
	@Override
	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;
	}

}

[/hide]

Now, its done, Check this if it works !

P.S. do not use emulator for this, test it on actual device


xQbgYbH.png
zpRgqbm.png
P6jkcjb.png

 
Last edited:

Nachiket.Namjoshi

Senior Member
Aug 16, 2012
710
2,054
◄♪♫██ ♪♫►

Top Liked Posts

  • There are no posts matching your filters.
  • 176
    Introduction

    Hello and Welcome to android app development guide. In this [guide] i will teachyou how to develop applications for the android platform using java and some simple tools. I will also teach you to add audio/video to your apps and also teach how to make them location aware by adding gps function to it :) :D :D

    What You Should Know

    Here I am just letting you all Know the pre-requisites of making an app. But then if you dont match the pre-requisites..... its OKAY !! I started it without this xD


    • Some Experience Of Object Oriented Programming
    • Some Experience of JAVA
    • Experience of Using ECLIPSE
    • Have An ANDROID phone so that you know the capabilities of Android


    73
    Activities And Explicit Intents

    Activities & Explicit Intents

    As I've already told you that Activities are one of the primary building blocks of your app. here, we will learn how to create actiities, declare them in AndroidManifest.xml and We will also learn How to go to another activity from one activity. Okay. So now open up Eclipse. and sart a new Android Project.

    • Click on File >> New >> Android Project
      LFZaf5w.png


    • Fill in the details as you wish.... and click finish. :)
      5xqJl84.png

    • After you make a Project. You will get A full working Hello world Application. now, modify the MainActivity.xml in the graphical part like this
      oQMSpKf.png

    • make a new xml file by clicking
      z6nUn8C.png
      . Give a file name like... SecondActivity.xml or something you like Note: This Will be your Second Activity. and now click Finish
    • Now drag the " TextView " from the " form widgets" tab from the left side panel to the graphical editor of your second activity.

    Now, Basically what i want to teach is Explicit Intents. Now what we want our app to do is the text written in the MainActivity should be shown to the user when he clicks the "go to second activity" button. So to do this, we need to declare and do something with JAVA !


    • navigate to the .java files -->

      quGL9ze.png

    • Double click the java file and you will et something like this ( gibberish... if you dont like java like me :p )
      vUirRq7.png

      hduDb3O.png


      since we need to define the "EditText" field and the "Button" from the first activity !

      Now, find this

      Code:
      setContentView(R.layout.main);


      after that start typing

      final EditText et = findView

      now press ctrl+space (windows)
      it will show you a list of commands. choose findViewById(id)
      now it will automatically place you along the (id). now start typing ---> R.id.
      and press ctrl+space (windows).
      chose the EditText Value..... Now as you see, it will show an error there. press ctrl+1 to show quick fixes. Add a cast to EditText. Final text will be Like this

      Code:
      final EditText et = (EditText) findViewById(R.id.editText1);


      Now do the same with the "Button"


      Code:
      Button b = (Button) findViewById(R.id.button1);

      Now that you have defined the button. Now you will have to set an OnClickListener for that button. so the it allows User to go to the second activity.

      now start typing

      b.setOnclick... press ctrl+space and choose onClickListener. It will automatically place you in the "()" type there --> new OnClickListener press ctrl+space. you will get something like this

      fTtEQFN.png


      you will get an error. so go to the place ( marked red in the pic and put a semi-colon )

      now, in the following method,

      Code:
      public void onClick(View arg0) {
      				// TODO Auto-generated method stub
      				
      				
      			}

      start typing the following

      Code:
      Intent intent = newInt

      press ctrl+space and choose this


      kl6CA4N.png


      It will automatically place you in packageContext.

      NOTE:

      packageContext == "The java file that is creating the Intent";
      cls == " The java file to whom the Intent Should be passed";



      so, edit it this way

      Code:
      Intent intent = new Intent(MainActivity.this, SecondActivity.class);

      NOTE:

      MainActivity == "The java file that you are editing";
      SecondActivity == " The java file That WILL represent the the SecondActivity.xml";



      It will give you an error. press ctrl+1 and select--> create class "SecondActivity"
      Fill in the details of the new java file and click finish. Now go back to previous java file.

      Now, you have created an intent. But its not defined that what will that intent do !
      So, now, Lets define that ;)

      start typing--> intent.putExtra and press ctrl+space. choose this.

      Q11uLpc.png


      now, you will be automatically placed in the "key". now for the key, you will have to type a string. i would like to call it "thetext". Now, Make sure you type the string WITHIN THE DOUBLE QUOTES..

      For the value, you will have to give the reference of the "EditText" Field. here, i have given it as "et", i will type it this way.

      intent.putExtra("thetext", et.getText().toString());

      Now, you have successfully DEFINED what the intent does. but if you check the coding..... you will notice that the intent is never initialised ! now, to initialise it, type in this -->
      startActivity(intent);
    the final MainActivity.java should look like this.

    TIJRky9.png





    Now, its almost done..... BUT.... ! what the hell is the use of the secondActivity.java o_O ! ?
    It is to be edited. only then the text written in the first activity by the user will be shown in the second activity. to do that, go to second activity. Now,



    EASY PART

    • Find this in the first java file:
      vUirRq7.png

      hduDb3O.png
    • Copy all that stuff to the SecondActivity.java
    • Change the blue highlited text ( in eclipse ) to the name of the second xml file. (just dont add the extension)


    Hard PART

    Now, you gotta define the "TextView" on the SecondActivity.xml Since you have given the reference to the SecondActivity.xml by copying all that stuff.

    so, start typing,

    Code:
    TextView tv = findView


    NOTE: Here "tv" is the name you have assigned to the "TextView". You can change it if you want. BUT makesure you do the cahnges accordingly in the next steps.

    hit ctrl + space. choose >> findViewById(id);

    now again, as we already did that before, in the place of "id" just type in "R.id." hit ctrl+space and chose the "TextView"

    Now, that You have defined it here, dosent mean that It will give you desired output....
    You just have created an intent and have defined it and initialised it in the last java file.
    But there is no-one to recieve that intent ! so, start typing the following:

    JURMrFy.png


    And, in place of text, start typing "getI" and press ctrl+space. put a fullstop, type "getE" hit ctrl+space, put a fullstop again, start typing "getS", ctrl+space again now in the "()" put the string that you have defined in the last java file. since I have defined it as "thetext" i will type that in the "()" like this:

    Code:
    tv.setText(getIntent().getExtras().getString("thetext"));



    Now, its done..... BUT.... ! .... AndroidManifest.xml
    you didnt touch it till now. we have to register every activity there. or else, the app will cause a FC error. (Force Closes)


    Now, open up the Androidmanifest.xml

    UMHSKeK.png


    go to the text editor :

    IbktDuE.png



    and in the end before--> "</application>" add this
    Code:
    <activity
                android:name="com.blksyn.explicitintents.SecondActivity">
    </activity>




    Now, its done. Lets start the emulator and Check this if it works !

    • Go to AVD Manager like this:
      D8aW8RF.png
    • Start the AVD emulator.
    • click on run: and click on run again xD. Click on okay.
      eNiT4s1.png

    Bingo ! you have created an app which declares Explicit Intents and added a function to activities to catch that intent !

    CavNt7h.png
    kLQfPLv.png





    72
    Overview

    Android Architecture


    • Runs on Linux 2.6
    • Dalvik Virtual Machine, Which Is optimised for mobiles
    • Integrated Browser, based On Webkit Engine
    • Optimized Graphics with Open GL ES
    • SQLite Database for Data storage
    Android Application Fundamentals

    • Applications are written in JAVA programming Language
    • Compiled Into Android Package file (.apk)
    • Each Application runs in its own sandbox and linux processes
    • Applications consists of Components, Resources and a Manifest file
    Components:

    • Activities
      • Single Screen with a UI [a screen seen by a user, it is an activity. basically a single screen, seen by the user IS an ACTIVITY ]
      • Multiple Activities are required to make a user friendly application ;)
      • When a new activity starts, old activity is pushed on to the Back Stack [ it becomes handy and fast if you press the back button on the phone. the activity on the back stack is not needed to be loaded again ! ]
      • UI can be built with either by XML ( recommended) or in Java ( I hate doing that :p )
      • You can manipulate the lifetime of the activities by certain call back methods. such as onStart[], onPause[], etc.
    • Services

      • They perform long-running operations in the background.
      • Doesn't contain ANY user interface
      • Useful for network operations, playing music, etc.
      • Runs independently of the component that created it ! --> [ say a service that launches a Service is closed. the service is still running ]
      • They can be bound to other application components. [ IF allowed ]
    • Content Providers
      • Used to store and retrieve data and make it accessible to any application.
      • Since, there is no way to share data across the applications, it is the only way !
      • Exposes a public URI that identifies the data set with some unique method or codes.
      • The data is exposed by a simple table on a database model concept.
      • Android contains many providers for things like contacts, media, etc.
    • Broadcast Recievers
      • A component that responds to system-wide broadcast announcement.
      • For Example, if the battery is low, Android Sends a system-wide broadcast, and the application that is listening to it, is responded by a Broadcast Reciever.
      • Applications can also initiate a broadcast that different applications can respond to ! example --> if an application, app1, is dependent on another application, app2, it can start a broadcast for app2. if the app2 exists, it can proceed else it will pop up a message like --- "app2 doesn't exist. plz download it from the market"
      • They, like services, contain no UI
      • Can be used to create Status Bar Notifications
    • Android Manifest File
      • All applications MUST have an AndroidManifest.xml in its root directory.
      • Presents the information about the application to the Android System.
      • Declares the Components used in the application
      • Also Declares the permissions required from the user to run the application.
      • Declares the Minimum Android API level to run that application. [ eg: GingerBread, HoneyComb, IceCreamSandwich, etc. ]



    Details About Some Folders
    Have You ever Decompiled any apk file ?? If not, do it, cuz it is really important part of app making. since there are many relative things to this.
    In here I will
    Explain about some folders you get to see in a folder named "res" when you decompile.

    • layout
      In This Folder, You will find some xmls, which looks more like a web page source :p
      And Gibberish until you take a CLOSE LOOK !
      It actually stores in the Layout of your activity. You will get to be familiar with this as we are going to use this :D
    • drawable
      In this folder, You will get the things that makes the app look beautiful !
      Ha! This contains "pngs" that are used in themes. We Will come to this as time passes
    • xml
      In here, Again, XMLs with someting Gibberish till you get a closer Look ! These xmls store your preference activities.
    • anim
      This folder, again xmls, which seem more unreadable. This folder, as the name says, it stores the anim files that has instructions for your animations that you (will) use in the app.
    • values
      This folder, again xmls, which seem even more unreadable. This folder, stores the values for different stuff, like ids, integers color hex's, etc (we will get to this later) .
    • colors
      This folder, again xmls, as the name says, stores the colors that you (will be) using in the app (we will get to this later) .
    63
    Implicit Intents

    Implicit Intents


    Now, you must have seen some applications with a "share" button. By clicking on this button, you can share a particular image/video/audio/etc....
    What does that application actually do is send a message to other applications to search for the applications capable of handling such type of job. Then it pops up the list of such apps to the user. Now we can also have that list contain our app too !
    Here is how.





    • Create a blank project. I gave it the name as "Implicit_intents". But you can choose whatever you want :)
    • Open up the "AndroidManifest.xml" file. (plz dont expect me to show how, cuz i have already shown that earlier and you should know that by now)
      You will see something like this

      001.PNG

    • Copy this from the main activity
      Code:
      	<intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
          	</intent-filter>

      paste it again after the </intent-filter>
      and change it to this

      Code:
      	<intent-filter>
                      <action android:name="android.intent.action.SEND" />
                      <category android:name="android.intent.category.DEFAULT" />
                      <data android:mimeType="image/*" />
          	</intent-filter>


      NOTE:
      Code:
      		<action android:name="android.intent.action.SEND" />

      (self explainatory)
      Code:
       <category android:name="android.intent.category.DEFAULT" />

      This tells the android system waht the category of the intent is. If you dont know what the category really is, you should keep it DEAFAULT.
      Code:
       <data android:mimeType="image/*" />

      This tells the Android system, What type of data can the application "SEND" (* reference to the first one). and "data/*" means that the application can handle any type of imge. Jpeg, png, bmp, etc....

    So, this is how your AndroidManifest.xml should look like.

    002.PNG



    • Now, go to the xml of your main activity and get rid of that text view. and add an "ImageView" from "Images and media" tab on the left


      003.PNG
    • Now, go to your main java file and give a refernece to that ImageView


      004.PNG


      NOTE: "iv" is just a name given to the ImageView. so, you can change it if you want. But you will have to adapt to it and make changes in the steps accordingly.

      Import the image view thing and add a cast by hitting ctrl+space
    • Now that you have specified the ImageView, you now have to set the ImageView to show the image the user wanna send. so, start typing in "iv.setImage" and press ctrl+space.

      005.png


      Now, since the image is IN the intent sent by the gallery after the user clicks the share button, we have to "get" the "EXTRAS" from the intent. So, start typing in in the "()". "getInt" press ctrl+space put a "." again type "getExt" choose the only option available, put a "." again and type "get" choose the first option. now, for the key, we are gonna use a constant from the INTENT class, that is called "EXTRA_STREAM". So ,just start typing in "Intent", put a ".", type "extra_" and choose "EXTRA_STREAM".


      This "EXTRA_STREAM" is nothing but the "URI" to the image the user wants to send. You will have an error now in the line even after putting a ";" in the end. so press the quick fix combo "ctrl+1" and add a cast to (URI).

      006.PNG



    Now, you have successfully built an application that can handle the "share" kind of intent. now if you run this app in the emulator, you will probably have an FC. Since the app does not have any intent to process during the launch, it will FC. but if you go to gallery and click on share, you will get this app in the list. And also, if you click on this app, you will see the image you wanted to share.


    So, this ends our chapter of Implicit Intents. You can now use your imaginations and use the combos of the previous and this chapter to build a pretty good basic app ! and the credit will be yours ! But dont forget to thank me for my efforts. haha... and also if i help you in some place.

    And last but not the least in this chapter, If you have any questions, post a reply in this thread :) you will surely be answered :D :D :good: