Friday, May 25, 2012

Lets do sign(Signature) on android phone


 DrawcanvasActivity:
public class DrawcanvasActivity extends Activity {

    public static final int SIGNATURE_ACTIVITY = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button getSignature = (Button) findViewById(R.id.signature);
        getSignature.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(DrawcanvasActivity.this, Capture.class);
                startActivityForResult(intent,SIGNATURE_ACTIVITY);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch(requestCode) {
        case SIGNATURE_ACTIVITY:
            if (resultCode == RESULT_OK) {

                Bundle bundle = data.getExtras();
                String status  = bundle.getString("status");
                if(status.equalsIgnoreCase("done")){
                    Toast toast = Toast.makeText(this, "Signature capture successful!", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 105, 50);
                    toast.show();
                }
            }
            break;
        }

    }

}


public class Capture extends Activity {

    LinearLayout mContent;
    signature mSignature;
    Button mClear, mGetSign, mCancel;
    public static String tempDir;
    public int count = 1;
    public String current = null;
    private Bitmap mBitmap;
    View mView;
    File mypath;

    private String uniqueId;
    private EditText yourName;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.signature);
     
     
     
        tempDir =Environment.getExternalStorageDirectory() + "/" + "canvasimage" + "/";
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("canvasimage",Context.MODE_PRIVATE);
     
     

        prepareDirectory();
        uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
        current = uniqueId + ".png";
        mypath= new File(directory,current);


        mContent = (LinearLayout) findViewById(R.id.linearLayout);
        mSignature = new signature(this, null);
        mSignature.setBackgroundColor(Color.WHITE);
        mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mClear = (Button)findViewById(R.id.clear);
        mGetSign = (Button)findViewById(R.id.getsign);
        mGetSign.setEnabled(false);
        mCancel = (Button)findViewById(R.id.cancel);
        mView = mContent;

        yourName = (EditText) findViewById(R.id.yourName);

        mClear.setOnClickListener(new OnClickListener()
        {      
            public void onClick(View v)
            {
                Log.v("log_tag", "Panel Cleared");
                mSignature.clear();
                mGetSign.setEnabled(false);
            }
        });

        mGetSign.setOnClickListener(new OnClickListener()
        {      
            public void onClick(View v)
            {
                Log.v("log_tag", "Panel Saved");
                boolean error = captureSignature();
                if(!error){
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    Bundle b = new Bundle();
                    b.putString("status", "done");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        });

        mCancel.setOnClickListener(new OnClickListener()
        {      
            public void onClick(View v)
            {
                Log.v("log_tag", "Panel Canceled");
                Bundle b = new Bundle();
                b.putString("status", "cancel");
                Intent intent = new Intent();
                intent.putExtras(b);
                setResult(RESULT_OK,intent);
                finish();
            }
        });

    }

    @Override
    protected void onDestroy() {
        Log.w("GetSignature", "onDestory");
        super.onDestroy();
    }

    private boolean captureSignature() {

        boolean error = false;
        String errorMessage = "";


        if(yourName.getText().toString().equalsIgnoreCase("")){
            errorMessage = errorMessage + "Please enter your Name\n";
            error = true;
        }

        if(error){
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 105, 50);
            toast.show();
        }

        return error;
    }

    private String getTodaysDate() {

        final Calendar c = Calendar.getInstance();
        int todaysDate =     (c.get(Calendar.YEAR) * 10000) +
        ((c.get(Calendar.MONTH) + 1) * 100) +
        (c.get(Calendar.DAY_OF_MONTH));
        Log.w("DATE:",String.valueOf(todaysDate));
        return(String.valueOf(todaysDate));

    }

    private String getCurrentTime() {

        final Calendar c = Calendar.getInstance();
        int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) +
        (c.get(Calendar.MINUTE) * 100) +
        (c.get(Calendar.SECOND));
        Log.w("TIME:",String.valueOf(currentTime));
        return(String.valueOf(currentTime));

    }


    private boolean prepareDirectory()
    {
        try
        {
            if (makedirs())
            {
                return true;
            } else {
                return false;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
            return false;
        }
    }

    private boolean makedirs()
    {
        File tempdir = new File(tempDir);
        if (!tempdir.exists())
            tempdir.mkdirs();

        if (tempdir.isDirectory())
        {
            File[] files = tempdir.listFiles();
            for (File file : files)
            {
                if (!file.delete())
                {
                    System.out.println("Failed to delete " + file);
                }
            }
        }
        return (tempdir.isDirectory());
    }

    public class signature extends View
    {
        private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();

        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();

        public signature(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(STROKE_WIDTH);
        }

        public void save(View v)
        {
            Log.v("log_tag", "Width: " + v.getWidth());
            Log.v("log_tag", "Height: " + v.getHeight());
            if(mBitmap == null)
            {
                mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
            }
            Canvas canvas = new Canvas(mBitmap);
            try
            {
                FileOutputStream mFileOutStream = new FileOutputStream(mypath);

                v.draw(canvas);
                mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
                mFileOutStream.flush();
                mFileOutStream.close();
                String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
                Log.v("log_tag","url: " + url);
                //In case you want to delete the file
                //boolean deleted = mypath.delete();
                //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                //If you want to convert the image to string use base64 converter

            }
            catch(Exception e)
            {
                Log.v("log_tag", e.toString());
            }
        }

        public void clear()
        {
            path.reset();
            invalidate();
        }

        @Override
        protected void onDraw(Canvas canvas)
        {
            canvas.drawPath(path, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();
            float eventY = event.getY();
            mGetSign.setEnabled(true);

            switch (event.getAction())
            {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(eventX, eventY);
                lastTouchX = eventX;
                lastTouchY = eventY;
                return true;

            case MotionEvent.ACTION_MOVE:

            case MotionEvent.ACTION_UP:

                resetDirtyRect(eventX, eventY);
                int historySize = event.getHistorySize();
                for (int i = 0; i < historySize; i++)
                {
                    float historicalX = event.getHistoricalX(i);
                    float historicalY = event.getHistoricalY(i);
                    expandDirtyRect(historicalX, historicalY);
                    path.lineTo(historicalX, historicalY);
                }
                path.lineTo(eventX, eventY);
                break;

            default:
                debug("Ignored touch event: " + event.toString());
                return false;
            }

            invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                    (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

            lastTouchX = eventX;
            lastTouchY = eventY;

            return true;
        }

        private void debug(String string){
        }

        private void expandDirtyRect(float historicalX, float historicalY)
        {
            if (historicalX < dirtyRect.left)
            {
                dirtyRect.left = historicalX;
            }
            else if (historicalX > dirtyRect.right)
            {
                dirtyRect.right = historicalX;
            }

            if (historicalY < dirtyRect.top)
            {
                dirtyRect.top = historicalY;
            }
            else if (historicalY > dirtyRect.bottom)
            {
                dirtyRect.bottom = historicalY;
            }
        }

        private void resetDirtyRect(float eventX, float eventY)
        {
            dirtyRect.left = Math.min(lastTouchX, eventX);
            dirtyRect.right = Math.max(lastTouchX, eventX);
            dirtyRect.top = Math.min(lastTouchY, eventY);
            dirtyRect.bottom = Math.max(lastTouchY, eventY);
        }
    }
}



<?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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:textSize="25sp" android:paddingBottom="20dp"
        android:textStyle="bold" />
    <Button android:text="Get My Signature" android:id="@+id/signature"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />



</LinearLayout>




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/linearLayout1"
    android:layout_width="600dp" android:layout_height="400dp"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout2" android:layout_width="match_parent">
        <Button android:layout_height="50dp" android:layout_weight=".30"
            android:text="Cancel" android:layout_width="0dp" android:id="@+id/cancel" />
        <Button android:layout_height="50dp" android:layout_weight=".35"
            android:text="Clear" android:layout_width="0dp" android:id="@+id/clear" />
        <Button android:layout_height="50dp" android:layout_weight=".35"
            android:text="Save" android:layout_width="0dp" android:id="@+id/getsign" />
    </LinearLayout>
    <TableLayout android:layout_height="wrap_content"
        android:id="@+id/tableLayout1" android:layout_width="match_parent">
        <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="Your Name" android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" android:paddingLeft="10sp"
                android:layout_gravity="right" />
            <EditText android:layout_height="wrap_content" android:id="@+id/yourName"
                android:layout_weight="1" android:layout_width="match_parent"
                android:maxLength="30">
                <requestFocus />
            </EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="" android:maxLength="30"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" />
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="Please Sign below ..." android:maxLength="30"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" />
        </TableRow>
    </TableLayout>
    <LinearLayout android:layout_height="match_parent"
        android:id="@+id/linearLayout" android:layout_width="match_parent" />
</LinearLayout>



Android Video Streaming Example


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class HelloAndroidActivity extends Activity implements OnClickListener {

private static String TAG = "androidEx2";
private Button buttonVideoSample;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.main);

buttonVideoSample = (Button) findViewById(R.id.buttonVideoSample);
buttonVideoSample.setOnClickListener(this);

}

public void onClick(View v) {

if (v.getId() == R.id.buttonVideoSample)

{
   //   http://podcast.20min-tv.ch/podcast/20min/199733.mp4
// HERE SET YOUR VIDEO URI   http://www.youtube.com/v/ZirgAYBcOgo&hl=en&fs=1
String video_uri = "http://www.youtube.com/watch?v=cxLG2wtE7TM";
Intent intent = new Intent(this, VideoSample.class);
intent.putExtra("video_path", video_uri);
startActivity(intent);
}
}

}



<?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:layout_height="wrap_content"
   android:layout_width="match_parent"
   android:id="@+id/buttonVideoSample"
   android:text="Click to Stream video">
 
</Button>

</LinearLayout>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class VideoSample extends Activity implements OnSeekBarChangeListener, Callback, OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener,
OnClickListener, OnSeekCompleteListener, AnimationListener {
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "androidEx2 = VideoSample";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videosample);
extras = getIntent().getExtras();

linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);

hideMediaController = AnimationUtils.loadAnimation(this, R.anim.disapearing);
hideMediaController.setAnimationListener(this);

imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.VISIBLE);
}
}

textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);

surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
surfaceViewFrame.setOnClickListener(this);
surfaceViewFrame.setClickable(false);

seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress.setOnSeekBarChangeListener(this);
seekBarProgress.setProgress(0);

progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);

holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
player.setDisplay(holder);
}

private void playVideo() {
if (extras.getString("video_path").equals("VIDEO_URI")) {
showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
} else {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource(extras.getString("video_path"));
player.prepare();
} catch (IllegalArgumentException e) {
showToast("Error while playing video");
Log.i(TAG, "========== IllegalArgumentException ===========");
e.printStackTrace();
} catch (IllegalStateException e) {
showToast("Error while playing video");
Log.i(TAG, "========== IllegalStateException ===========");
e.printStackTrace();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IOException ===========");
e.printStackTrace();
}
}
}).start();
}
}

private void showToast(final String string) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VideoSample.this, string, Toast.LENGTH_LONG).show();
finish();
}
});
}

private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress + " from user: " + fromUser);
if (!fromUser) {
textViewPlayed.setText(Utils.durationInSecondsToString(progress));
}
}

public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

public void onStopTrackingTouch(SeekBar seekBar) {
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(seekBar.getProgress() * 1000);
Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
}
}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub

}

public void surfaceCreated(SurfaceHolder holder) {
playVideo();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
               // player.stop();
}

public void onPrepared(MediaPlayer mp) {
Log.i(TAG, "========== onPrepared ===========");
int duration = mp.getDuration() / 1000; // duration in seconds
seekBarProgress.setMax(duration);
textViewLength.setText(Utils.durationInSecondsToString(duration));
progressBarWait.setVisibility(View.GONE);

// Get the dimensions of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: " + videoHeight + " PROP: " + videoProportion);

// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: " + screenHeight + " PROP: " + screenProportion);

// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();

if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}

// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);

// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
}

public void onCompletion(MediaPlayer mp) {
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}

/**
* Change progress of mediaController
* */
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
seekBarProgress.setProgress(player.getCurrentPosition() / 1000);
}
});
}
}, 0, 1000);
}

public void onBufferingUpdate(MediaPlayer mp, int percent) {
int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}

public void onClick(View v) {
if (v.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
} else if (player != null) {
if (player.isPlaying()) {
player.pause();
imageViewPauseIndicator.setVisibility(View.VISIBLE);
} else {
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
}

public void onSeekComplete(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
}

public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub

}

public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

public void onAnimationStart(Animation animation) {
linearLayoutMediaController.setVisibility(View.GONE);
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
   android:layout_width="match_parent" 
   android:layout_height="match_parent" 
   android:id="@+id/frameLayoutRoot"
   >
   
<SurfaceView 
   android:id="@+id/surfaceViewFrame" 
   android:layout_gravity="center" 
   android:layout_height="wrap_content" 
   android:layout_width="wrap_content">
   
</SurfaceView>
<LinearLayout 
   
   android:layout_width="match_parent" 
   android:id="@+id/linearLayoutMediaController" 
   android:layout_height="wrap_content" 
   android:paddingBottom="5dp"
android:paddingTop="5dp" 
android:layout_gravity="bottom" 
android:gravity="center_vertical" 
android:background="@color/media_controller_bg_color"
>
<TextView 
   android:layout_width="wrap_content" 
   android:id="@+id/textViewPlayed" 
   android:layout_marginLeft="5dp" 
   android:layout_marginRight="5dp"
android:textColor="@color/media_controller_text_color" 
android:textStyle="bold" 
android:text="0:00:00"
android:padding="0dp" 
android:textSize="13sp" 
android:gravity="center"
android:layout_height="wrap_content">
   
</TextView>
<SeekBar 
   android:id="@+id/seekBarProgress" 
   android:layout_weight="1"    
   style="@style/MyCustomProgressStyle" 
   android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:progress="50">
   
</SeekBar>
<TextView 
   android:layout_width="wrap_content" 
   android:id="@+id/textViewLength" 
   android:layout_marginLeft="5dp" 
   android:layout_marginRight="5dp"
android:textColor="@color/media_controller_text_color" 
android:textStyle="bold" 
android:text="0:00:00" 
android:textSize="13sp"
android:padding="0dp" 
android:gravity="center"
android:layout_height="wrap_content">
   
</TextView>
</LinearLayout>
<ProgressBar 
   style="?android:attr/progressBarStyleLarge" 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:layout_gravity="center"
android:id="@+id/progressBarWait">
   
</ProgressBar>
<ImageView
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:id="@+id/imageViewPauseIndicator" 
   android:layout_gravity="center"
android:src="@drawable/pause_button">
   
</ImageView>
</FrameLayout>

</LinearLayout>



/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Utils {
public static String durationInSecondsToString(int sec){
int hours = sec / 3600; 
int minutes = (sec / 60) - (hours * 60);
int seconds = sec - (hours * 3600) - (minutes * 60) ;
String formatted = String.format("%d:%02d:%02d", hours, minutes, seconds);
return formatted;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


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

Map Dispaly on Android Phone


MapDemo.java:
public class MapDemoActivity extends MapActivity {

private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay;
private MyLocationOverlay myLocationOverlay;

public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity

// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());

myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);

myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});

Drawable drawable = this.getResources().getDrawable(R.drawable.pin);
itemizedoverlay = new MyOverlays(this, drawable);
createMarker();
}

@Override
protected boolean isRouteDisplayed() {
return false;
}

public class GeoUpdateHandler implements LocationListener {

@Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);

}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
if (itemizedoverlay.size() > 0) {
mapView.getOverlays().add(itemizedoverlay);
}
}

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

@Override
protected void onPause() {
super.onResume();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
}

overlay Class:


public class MyOverlays extends ItemizedOverlay<OverlayItem> {

private static int maxNum = 5;
private OverlayItem overlays[] = new OverlayItem[maxNum];
private int index = 0;
private boolean full = false;
private Context context;
private OverlayItem previousoverlay;

public MyOverlays(Context context, Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
this.context = context;
}

@Override
protected OverlayItem createItem(int i) {
return overlays[i];
}

@Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}

}

public void addOverlay(OverlayItem overlay) {
if (previousoverlay != null) {
if (index < maxNum) {
overlays[index] = previousoverlay;
} else {
index = 0;
full = true;
overlays[index] = previousoverlay;
}
index++;
populate();
}
this.previousoverlay = overlay;
}

protected boolean onTap(int index) {
@SuppressWarnings("unused")
OverlayItem overlayItem = overlays[index];
Builder builder = new AlertDialog.Builder(context);
builder.setMessage("This will end the activity");
builder.setCancelable(true);
builder.setPositiveButton("I agree", new OkOnClickListener());
builder.setNegativeButton("No, no", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
return true;
};

private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "You clicked yes", Toast.LENGTH_LONG)
.show();
}
}

private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "You clicked no", Toast.LENGTH_LONG).show();
}
}
}



main.xml:


<com.google.android.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="your key"
    android:clickable="true" />


manifest.xml:


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

<uses-library android:name="com.google.android.maps" />