Friday, May 4, 2012

Check and prompt user to enable GPS


Check and prompt user to enable GPS

To check if the GPS have been enabled or not, the following code can be used:

String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

If it's empty, means the GPS have not been enabled. You can start activity with intentSettings.ACTION_SECURITY_SETTINGS, to switch to GPS setting page.




package com.exercise.AndroidEnableGPS;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

public class AndroidEnableGPS extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       CheckEnableGPS();
   }
  
   private void CheckEnableGPS(){
    String provider = Settings.Secure.getString(getContentResolver(),
      Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
       if(!provider.equals("")){
           //GPS Enabled
        Toast.makeText(AndroidEnableGPS.this, "GPS Enabled: " + provider,
          Toast.LENGTH_LONG).show();
       }else{
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
           startActivity(intent);
       }

   }
}

My location and Google Map

My location and Google Map


This is very good example for getting user location with the map  
and display in the map with circle like in the goggle map with twinkling bubble 








package app.test;

import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class MyLocationDemoActivity extends MapActivity {
    
    MapView mapView = null;
    MapController mapController = null;
    MyLocationOverlay whereAmI = null;
    
    @Override
    protected boolean isLocationDisplayed() {
        return whereAmI.isMyLocationEnabled();
    }
    
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mapView = (MapView)findViewById(R.id.geoMap);
        mapView.setBuiltInZoomControls(true);

        mapController = mapView.getController();
        mapController.setZoom(15);

        whereAmI = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(whereAmI);
        mapView.postInvalidate();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        whereAmI.enableMyLocation();
        whereAmI.runOnFirstFix(new Runnable() {
            public void run() {
                mapController.setCenter(whereAmI.getMyLocation());
            }
        });
    }

    @Override
    public void onPause()
    {
        super.onPause();
        whereAmI.disableMyLocation();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

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

</RelativeLayout>

Play video from Youtube.com

Play video from Youtube.com

package 
app.test;

import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.MediaController;

public class Test extends Activity implements
    OnCompletionListener, OnErrorListener, OnInfoListener,
    OnBufferingUpdateListener, OnPreparedListener, OnSeekCompleteListener,
    OnVideoSizeChangedListener, SurfaceHolder.Callback,
    MediaController.MediaPlayerControl {

  MediaController controller;
  Display currentDisplay;
  SurfaceView surfaceView;
  SurfaceHolder surfaceHolder;
  MediaPlayer mediaPlayer;

  View mainView;
  TextView statusView;

  int videoWidth = 0,videoHeight = 0;

  boolean readyToPlay = false;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    mainView = this.findViewById(R.id.MainView);

    statusView = (TextViewthis.findViewById(R.id.StatusTextView);

    surfaceView = (SurfaceViewthis.findViewById(R.id.SurfaceView);
    surfaceHolder = surfaceView.getHolder();

    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mediaPlayer = new MediaPlayer();

    statusView.setText("MediaPlayer Created");

    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnVideoSizeChangedListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);

    String filePath = "rtsp://youtube.com/video.3gp";// your url here 
    try {
      mediaPlayer.setDataSource(filePath);
    catch (Exception e) {
      finish();
    }

    statusView.setText("MediaPlayer DataSource Set");
    currentDisplay = getWindowManager().getDefaultDisplay();
    controller = new MediaController(this);
  }

  public void surfaceCreated(SurfaceHolder holder) {
    mediaPlayer.setDisplay(holder);
    statusView.setText("MediaPlayer Display Surface Set");

    try {
      mediaPlayer.prepareAsync();
    catch (Exception e) {
      finish();
    }

    statusView.setText("MediaPlayer Preparing");
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {
  }
  public void surfaceDestroyed(SurfaceHolder holder) {
  }
  public void onCompletion(MediaPlayer mp) {
    statusView.setText("MediaPlayer Playback Completed");
  }

  public boolean onError(MediaPlayer mp, int whatError, int extra) {
    statusView.setText("MediaPlayer Error");
    if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
      Log.v("""Media Error, Server Died " + extra);
    else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
      Log.v("""Media Error, Error Unknown " + extra);
    }
    return false;
  }

  public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
    statusView.setText("MediaPlayer onInfo Called");
    if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
      Log.v("""Media Info, Media Info Bad Interleaving " + extra);
    else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
      Log.v("""Media Info, Media Info Not Seekable " + extra);
    else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
      Log.v("""Media Info, Media Info Unknown " + extra);
    else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
      Log.v("""MediaInfo, Media Info Video Track Lagging " + extra);
    else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) { 
      Log.v("","MediaInfo, Media Info Metadata Update " + extra)}
    return false;
  }

  public void onPrepared(MediaPlayer mp) {
    statusView.setText("MediaPlayer Prepared");
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();
    if (videoWidth > currentDisplay.getWidth()
        || videoHeight > currentDisplay.getHeight()) {
      float heightRatio = (floatvideoHeight
          (floatcurrentDisplay.getHeight();
      float widthRatio = (floatvideoWidth
          (floatcurrentDisplay.getWidth();
      if (heightRatio > || widthRatio > 1) {
        if (heightRatio > widthRatio) {
          videoHeight = (intMath.ceil((floatvideoHeight
              (floatheightRatio);
          videoWidth = (intMath.ceil((floatvideoWidth
              (floatheightRatio);
        else {
          videoHeight = (intMath.ceil((floatvideoHeight
              (floatwidthRatio);
          videoWidth = (intMath.ceil((floatvideoWidth
              (floatwidthRatio);
        }
      }
    }

    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
        videoHeight));
    controller.setMediaPlayer(this);
    controller.setAnchorView(this.findViewById(R.id.MainView));
    controller.setEnabled(true);
    controller.show();

    mp.start();
    statusView.setText("MediaPlayer Started");
  }

  public void onSeekComplete(MediaPlayer mp) {
  }

  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    videoWidth = mp.getVideoWidth();
    videoHeight = mp.getVideoHeight();
    if (videoWidth > currentDisplay.getWidth()
        || videoHeight > currentDisplay.getHeight()) {
      float heightRatio = (floatvideoHeight
          (floatcurrentDisplay.getHeight();
      float widthRatio = (floatvideoWidth
          (floatcurrentDisplay.getWidth();

      if (heightRatio > || widthRatio > 1) {
        if (heightRatio > widthRatio) {
          videoHeight = (intMath.ceil((floatvideoHeight
              (floatheightRatio);
          videoWidth = (intMath.ceil((floatvideoWidth
              (floatheightRatio);
        else {
          videoHeight = (intMath.ceil((floatvideoHeight
              (floatwidthRatio);
          videoWidth = (intMath.ceil((floatvideoWidth
              (floatwidthRatio);
        }
      }
    }

    surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
        videoHeight));
  }

  public void onBufferingUpdate(MediaPlayer mp, int bufferedPercent) {
    statusView.setText("MediaPlayer Buffering: " + bufferedPercent + "%");
  }
  public boolean canPause() {
    return true;
  }
  public boolean canSeekBackward() {
    return true;
  }
  public boolean canSeekForward() {
    return true;
  }
  public int getBufferPercentage() {
    return 0;
  }
  public int getCurrentPosition() {
    return mediaPlayer.getCurrentPosition();
  }

  public int getDuration() {
    return mediaPlayer.getDuration();
  }
  public boolean isPlaying() {
    return mediaPlayer.isPlaying();
  }
  public void pause() {
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.pause();
    }
  }
  public void seekTo(int pos) {
    mediaPlayer.seekTo(pos);
  }
  public void start() {
    mediaPlayer.start();
  }
  @Override
  public boolean onTouchEvent(MotionEvent ev) {
    if (controller.isShowing()) {
      controller.hide();
    else {
      controller.show();
    }
    return false;
  }
}

//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"
    android:id="@+id/MainView"
    >
  <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/StatusTextView" android:text="@+id/Status"></TextView>
  <SurfaceView android:id="@+id/SurfaceView" android:layout_height="200dip" android:layout_width="200dip"></SurfaceView>
</LinearLayout>