Showing posts with label android application. Show all posts
Showing posts with label android application. Show all posts

Monday, September 9, 2013

ShakeListener Example

Android device has advance function,It has hardware to detect shake event.It can also detect the direction of shaking device.This advance function measure the value of X, Y and Z direction.Screenshot of Shake Listener is given below.

How to Develop ?

  • Create one Project named "ShakeListener".
  • Insert below code in activity_main.xml file which is stored in res/layout directory of project folder.

activity_main.xml


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

        <TableLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:stretchColumns="0|1">
        
                <TableRow>
                
                        <TextView
                                android:text="X :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/x"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="Y :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/y"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="Z :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/z"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aX :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/ax"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aY :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/ay"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aZ"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/az"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
                
        </TableLayout>

</LinearLayout>



  • Now Open MainActivity.java file and insert Following code in it.

MainActivity.java

public class MainActivity extends Activity implements SensorEventListener {
    
        SensorManager sensorManager = null;
    private TextView x, y, z, ax, ay, az;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        setContentView(R.layout.activity_main);
        // initialize display
        x = (TextView) findViewById(R.id.x);
        y = (TextView) findViewById(R.id.y);
        z = (TextView) findViewById(R.id.z);
        ax = (TextView) findViewById(R.id.ax);
        ay = (TextView) findViewById(R.id.ay);
        az = (TextView) findViewById(R.id.az);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_GAME);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        sensorManager.unregisterListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION));
        sensorManager.unregisterListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER));
    }
    
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
        
        public void onSensorChanged(SensorEvent event) {
                synchronized (this) {
                switch (event.sensor.getType()) {
                        case SensorManager.SENSOR_ORIENTATION :
                                x.setText(String.valueOf(event.values[SensorManager.DATA_X]));
                                y.setText(String.valueOf(event.values[SensorManager.DATA_Y]));
                                z.setText(String.valueOf(event.values[SensorManager.DATA_Z]));
                                break;
                        case SensorManager.SENSOR_ACCELEROMETER :
                                ax.setText(String.valueOf(event.values[SensorManager.DATA_X]));
                                ay.setText(String.valueOf(event.values[SensorManager.DATA_Y]));
                                az.setText(String.valueOf(event.values[SensorManager.DATA_Z]));
                                break;
                }           
        }
        } 
        
}


  • If you get few errors then press CTRL+SHIFT+O. It imports all missing libraries.
  • That's It. Now run the project.

Get Full Source Code: FREE




Accelerometer full source code

Accelerometer in android, the value would show acceleration in X, Y and Z direction.Sample code is available in SDK manager.If you can't see it,Don't worry. Here is the full source code is available. 



Download Full Source Code:  FREE




Friday, September 6, 2013

Send Mail Automatically without Intent Tutorial

You can use intent to send mail.It uses inbuilt Email application to send mail.You can also send mail without using inbuilt email application.You need to have knowledge of SMTP (Simple Mail Transfer Protocol). There are many libraries available for send mail automatically.I use some of that for this tutorial.

Before we begin you need to download few library files and java class files.


  1. Auto send Mail Libraries
  2. Java Class Files

After Download above RAR, Extract it.

Here is the full description of project below, I will go through step by step.


  • Create android project named "SendEmailAuto".
  • Now Add library files (Above First Link) to your project (Right click your project > Properties > Java Build Path > Libraries > Add External JARs. Now Go to Order and Export Tab > Checked all JARs and press OK button)
  • Add Java class files (Above second link) into project src folder.Your Project Hierarchy is look like:



  • Now add following code in activity_main.xml

activity_main.xml



<ScrollView 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" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="25dp" >

        <EditText
            android:id="@+id/etemail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Enter Your Email ID"
            android:inputType="textEmailAddress"
            android:lines="1" />

        <EditText
            android:id="@+id/etPass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Enter Your Password"
            android:inputType="textPassword"
            android:lines="1" />

        <Button
            android:id="@+id/btnCompose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Compose" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            android:id="@+id/composeLinear"
            android:orientation="vertical" >

            <EditText
                android:id="@+id/etTo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="To"
                android:lines="1" >

                <requestFocus />
            </EditText>

            <EditText
                android:id="@+id/etSubject"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Subject"
                android:lines="1" />

            <EditText
                android:id="@+id/etBody"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:gravity="left|top"
                android:hint="Enter Text Here"
                android:lines="10" />

            <Button
                android:id="@+id/btnSend"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Send" />
        </LinearLayout>
    </LinearLayout>

</ScrollView>


  • Add following code in MainActivity.java

MainActivity.java


public class MainActivity extends Activity {

Button btnSend,btnCompose;
EditText etemailId,etPass,etTo,etSub,etBody;
String emailId,spass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button)findViewById(R.id.btnSend);
btnCompose = (Button)findViewById(R.id.btnCompose);
etemailId = (EditText)findViewById(R.id.etemail);
etPass = (EditText)findViewById(R.id.etPass);
etTo = (EditText)findViewById(R.id.etTo);
etSub = (EditText)findViewById(R.id.etSubject);
etBody = (EditText)findViewById(R.id.etBody);
final LinearLayout layout= (LinearLayout)findViewById(R.id.composeLinear);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String sub = etSub.getText().toString();
String to = etTo.getText().toString();
String body = etBody.getText().toString();
try {   
       GmailSender sender = new GmailSender(emailId, spass);
       sender.sendMail(sub,body,emailId,to);  
       Toast.makeText(getApplicationContext(),"Mail has been sent.",Toast.LENGTH_SHORT).show();
   } catch (Exception e) {   
    Toast.makeText(getApplicationContext(),"Error! Try again later.",Toast.LENGTH_SHORT).show();
   }
}
});
btnCompose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
emailId = etemailId.getText().toString();
spass = etPass.getText().toString();
if(emailId.equals("") || spass.equals("")){
Toast.makeText(getApplicationContext(),"Email ID and Password fields are mandatory.",Toast.LENGTH_SHORT).show();
}else{
layout.setVisibility(View.VISIBLE);
}
}
});
}
}

  • If you get error,Don't worry. Just press Ctrl + Shift + O button. It will import all missing libraries.
  • Don't forget to give internet permission in AndroidMenifest.xml file.
  • Open AndroidMenifest.xml file and add below permissions, before <application> tag.

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  • Done ! Now run the project.
NOTE : Don't use Android emulator for testing,It will not work on Android emulator. Use real android device for testing.Before run this project check your emailID and password.  

Download Full Source code : Download


Monday, September 2, 2013

How to play saved video in android?


  • Create android project named "savedVideoView".
  • Now create 'raw' folder in 'res' directory.Note: Do not change the folder name.
  • Add Video file (mp4) which you want to play in application.
  • Now just add following code in activity_main.xml file 

activity_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:gravity="center"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >
<VideoView android:id="@+id/welcome"
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:fitsSystemWindows="true"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >
</VideoView>
</LinearLayout>



  • Add following code in MainActivity.java file.

MainActivity.java



public class MainActivity extends Activity 
{

VideoView vv;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
// it is used to set full screen video
    requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);  

    setContentView(R.layout.play_intro);
    vv = (VideoView) findViewById(R.id.welcome);

       
    MediaController mc = new MediaController(this); 
    vv.setMediaController(mc); 
    mc.hide();
          // Here resource is 'video2' video file which is stored in 'raw' directory 
    vv.setVideoURI(Uri.parse("android.resource://com.tumbi/"+R.raw.video2));
   
    vv.start();
   
    vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
   
    @Override
    public void onCompletion(MediaPlayer mp) 
    {
    onPause();
                         // After completion of video it goes to CompleteVideoActivity automatically
    Intent i=new Intent(MainActivity.this,CompleteVideoActivity.class);
    startActivity(i);
    android.os.Process.killProcess(android.os.Process.myPid());
    }
    });
   
}

public void onPause ()
{
super.onPause();
vv.stopPlayback();
}
}

  • Done ! Now run the Project and get the O/P.

how to play youtube video in videoview android ?


how to play youtube video in videoview android ?

You can play youtube video in your application.There is no need to add third party library or other API.


  • First of all create one android project named "VideoViewTube".
  • You need to add VideoView component in your xml file.Open activity_main.xml and add following code:

activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fitsSystemWindows="true"
        android:minHeight="480dip"
        android:minWidth="854dip" />

</LinearLayout>


  • If your internet speed is low then It will take some time to play youtube video,Between buffering time and playing time your application UI may freeze.
  • To resolve this issue use Async Task (AsyncTask Tutorial).
  • Open MainActivity.java file and create MyAsyncTask class in below onCreate() method. 
  • MyAsyncTask class extends AsyncTask<Void,Void,Void>,Write following code in MyAsyncTask class.


private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=OtLa7wDpuOU";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
        
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(MainActivity.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }


  •  Now you get one error in  getUrlVideoRTSP(url).It is because youtube video is RTSP type videos RTSP means Real Time Streaming Protocol.We need to get Video URL from RTSP.
  • Add following two methods below MyAsyncTask class. getUrlVideoRTSP(String urlYoutube); and extractYoutubeId(String url);  


public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException    {        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }


  • Now just define VideoView and call AsyncTask Class in onCreate() Method.

MainActivity.java


public class MainActivity extends Activity {
VideoView videoView;
String videoUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.videoView);
new YourAsyncTask().execute();
}


  • At last write onPause method in bottom of MainActivity.java class
public void onPause ()
{
super.onPause();
videoView.stopPlayback();
}


The Completed MainActivity.java Class is : Part 2

Get Full Suorce Code: Here



VideoView Part2


MainActivity.Java


package com.example.videoview;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

VideoView videoView;
String videoUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.videoView);
/* String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp";

videoView.setVideoURI(Uri.parse(SrcPath));
      videoView.setMediaController(new MediaController(this));
      videoView.requestFocus();
      videoView.start();*/
new YourAsyncTask().execute();
}

private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=OtLa7wDpuOU";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
/*
            videoView.setVideoURI(Uri.parse("rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQk4RDShYkdS1BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"));
            videoView.setMediaController(new MediaController(AlertDetail.this));
            videoView.requestFocus();
            videoView.start();*/            
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(MainActivity.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }

public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }
public void onPause ()
{
super.onPause();
videoView.stopPlayback();
}
}


Get Full Source Code: Here