Friday 28 October 2011

Android First program Hello_World step by step.

 1.Download the eclipse -directly from here  (for window 32-bit only). 
    for other visit www.eclipse.org

2.Download window installer - from here

 3.Download ADT plug-in-- from here

 4.Now install the window installer downloaded in step-2

5.start the SDK manager.

6. Download the android platform (will take time). You must download at least one platform.

7.Open Eclipse and go to window option and then prefrence in eclipse and browse the android-sdk folder generally

it is located in C:\Program File\Android\android-sdk and click apply and then OK.

8.Now goto help and then install new software

9.Click on Add button Browse the ADT plug-in zip file(downloaded in step-3) click next now ADT plug-in

is installed.

.10.After finishing download in eclipse goto file->new project->Android

11.Give any name of project choose the sdk version (any one) give the application
name (anything).

Give the package name like com.example.myapp.

Give the activity name whatever you want.

Click finish

Your activity will open and something is already written in it

Like

Public void onCreate(……………..)

This is your main function .

112. now write it so that it look like.

package com.example.helloandroid;//your given package name

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {
/** Called when the
activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv =
new TextView(this);
tv.setText("Hello,
Android");
setContentView(tv);
} }

Now save it and right click on project and run it.

That is your hello, Android application.

Wednesday 12 October 2011

Android video player demo which stream vedio from the given URL

Today i am going to show you how can you make your own video player in android
which stream video on mobile
Make a new android project in eclipse.
Now copy the code given below in your main activity.


package org.android.sunny;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.VideoView;

public class VideoViewDemo extends Activity {
    private static final String TAG = "VideoViewDemo";

    private VideoView mVideoView;
    private EditText mPath;
    private ImageButton mPlay;
    private ImageButton mPause;
    private ImageButton mReset;
    private ImageButton mStop;
    private String current;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        mVideoView = (VideoView) findViewById(R.id.surface_view);

        mPath = (EditText) findViewById(R.id.path);
        mPath.setText("http://daily3gp.com/vids/747.3gp");

        mPlay = (ImageButton) findViewById(R.id.play);
        mPause = (ImageButton) findViewById(R.id.pause);
        mReset = (ImageButton) findViewById(R.id.reset);
        mStop = (ImageButton) findViewById(R.id.stop);

        mPlay.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                playVideo();
            }
        });
        mPause.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                if (mVideoView != null) {
                    mVideoView.pause();
                }
            }
        });
        mReset.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                if (mVideoView != null) {
                    mVideoView.seekTo(0);
                }
            }
        });
        mStop.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                if (mVideoView != null) {
                    current = null;
                    mVideoView.stopPlayback();
                }
            }
        });
        runOnUiThread(new Runnable(){
            public void run() {
                playVideo();
               
            }
           
        });
    }

    private void playVideo() {
        try {
            final String path = mPath.getText().toString();
            Log.v(TAG, "path: " + path);
            if (path == null || path.length() == 0) {
                Toast.makeText(VideoViewDemo.this, "File URL/path is empty",
                        Toast.LENGTH_LONG).show();

            } else {
                // If the path has not changed, just start the media player
                if (path.equals(current) && mVideoView != null) {
                    mVideoView.start();
                    mVideoView.requestFocus();
                    return;
                }
                current = path;
                mVideoView.setVideoPath(getDataSource(path));
                mVideoView.start();
                mVideoView.requestFocus();

            }
        } catch (Exception e) {
            Log.e(TAG, "error: " + e.getMessage(), e);
            if (mVideoView != null) {
                mVideoView.stopPlayback();
            }
        }
    }

    private String getDataSource(String path) throws IOException {
        if (!URLUtil.isNetworkUrl(path)) {
            return path;
        } else {
            URL url = new URL(path);
            URLConnection cn = url.openConnection();
            cn.connect();
            InputStream stream = cn.getInputStream();
            if (stream == null)
                throw new RuntimeException("stream is null");
            File temp = File.createTempFile("mediaplayertmp", "dat");
            temp.deleteOnExit();
            String tempPath = temp.getAbsolutePath();
            FileOutputStream out = new FileOutputStream(temp);
            byte buf[] = new byte[128];
            do {
                int numread = stream.read(buf);
                if (numread <= 0)
                    break;
                out.write(buf, 0, numread);
            } while (true);
            try {
                stream.close();
            } catch (IOException ex) {
                Log.e(TAG, "error: " + ex.getMessage(), ex);
            }
            return tempPath;
        }
    }
}




Now your layout :

<?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"
        >
    <EditText android:id="@+id/path"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
            />
    <VideoView android:id="@+id/surface_view"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent">
    </VideoView>
    <LinearLayout
            android:orientation="horizontal"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            >  
        <ImageButton android:id="@+id/play"
                     android:layout_height="wrap_content"
                     android:layout_width="wrap_content"
                     android:src="@drawable/play"/>

        <ImageButton android:id="@+id/pause"
                     android:layout_height="wrap_content"
                     android:layout_width="wrap_content"
                     android:src="@drawable/pause"/>
        <ImageButton android:id="@+id/reset"
                     android:layout_height="wrap_content"
                     android:layout_width="wrap_content"
                     android:src="@drawable/reset"/>
        <ImageButton android:id="@+id/stop"
                     android:layout_height="wrap_content"
                     android:layout_width="wrap_content"
                     android:src="@drawable/stop"/>
    </LinearLayout>
</LinearLayout>




 IMPORTANT NOTES: 1.DON'T FORGET TO PUT PLAY,PAUSE,STOP,RESET BUTTONS ( IMAGEVIEW ) .PNG IN DRAWABLE FOLDER YOU CAN DOWNLOAD THESE IMAGES JUST BY GOOGLING THEM.

2.DON'T FORGET TO ADD INTERNET PERMISSION IN YOUR MANIFEST FILE.

3. ENJOY!!!!!!!

Saturday 8 October 2011

Sending and Receiving messages in Android

Hello there, Today i am going to show you how can you send or receive messages.

 First make the a class which will extends the BroadcastReceiver as below

package YOUR PACKAGE NAME;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

class SMSReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null) {
          Object[] pdus = (Object[]) bundle.get("pdus");
          msgs = new SmsMessage[pdus.length];
          for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
          }
          Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
          Intent mainActivityIntent = new Intent(context, SMS.class);
          mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(mainActivityIntent);
          Intent broadcastIntent = new Intent();
          broadcastIntent.setAction("SMS_RECEIVED_ACTION");
          broadcastIntent.putExtra("sms", str);
          context.sendBroadcast(broadcastIntent);
        }
      }
    }

Now  your Main Activity should look like

package YOUR PACKAGE NAME;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class SMS extends Activity {
      Button btnSendSMS;
      IntentFilter intentFilter;
      private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          TextView SMSes = (TextView) findViewById(R.id.textView1);
          SMSes.setText(intent.getExtras().getString("sms"));
        }
      };

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        intentFilter = new IntentFilter();
        intentFilter.addAction("SMS_RECEIVED_ACTION");
        registerReceiver(intentReceiver, intentFilter);
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        btnSendSMS.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
            sendSMS("5554", "Hello my friends!");
            Intent i = new Intent(android.content.Intent.ACTION_VIEW);
            i.putExtra("address", "5556; 5558; 5560");
            i.putExtra("sms_body", "Hello my friends!");
            i.setType("vnd.android-dir/mms-sms");
            startActivity(i);
          }
        });
      }

      @Override
      protected void onResume() {
        super.onResume();
      }

      @Override
      protected void onPause() {
        super.onPause();
      }

      @Override
      protected void onDestroy() {
        unregisterReceiver(intentReceiver);
        super.onPause();
      }

      /*
       * private void sendSMS(String phoneNumber, String message) { SmsManager sms
       * = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
       * message, null, null); }
       */
      private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
            SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        registerReceiver(new BroadcastReceiver() {
          @Override
          public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
              Toast.makeText(getBaseContext(), "SMS sent",
                  Toast.LENGTH_SHORT).show();
              break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
              Toast.makeText(getBaseContext(), "Generic failure",
                  Toast.LENGTH_SHORT).show();
              break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
              Toast.makeText(getBaseContext(), "No service",
                  Toast.LENGTH_SHORT).show();
              break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
              Toast.makeText(getBaseContext(), "Null PDU",
                  Toast.LENGTH_SHORT).show();
              break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
              Toast.makeText(getBaseContext(), "Radio off",
                  Toast.LENGTH_SHORT).show();
              break;
            }
          }
        }, new IntentFilter(SENT));

        registerReceiver(new BroadcastReceiver() {
          @Override
          public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
              Toast.makeText(getBaseContext(), "SMS delivered",
                  Toast.LENGTH_SHORT).show();
              break;
            case Activity.RESULT_CANCELED:
              Toast.makeText(getBaseContext(), "SMS not delivered",
                  Toast.LENGTH_SHORT).show();
              break;
            }
          }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
      }

    }

XML file Layout :

<?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"
    >
<Button
    android:id="@+id/btnSendSMS" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send SMS" />   
   
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
   
</LinearLayout>


Just save all three files And most Impotent ADD THE PERMISSIONS IN YOUR MANIFEST FILE AS
<uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>

Run the application.Now to test the application just start another application  or emulator now you have two emulator running .first in which your sms app is running and second is in which your other app(any) app is running. now to test receiving just send the sms from second emulator to the emulator in which your sms app is running.(you can send sms by pre installed sms app). Ph no. is simply the emulator number like 5554 or 5556. similarly you can send the sms from your app and test it on second emulator.