Play Online Video in Android Device

In this post you can learn android source code example on how to play a video from a URL online from an android device. The basic functionality part is given below. This can be used in android application development for live video streaming from a URL. Using this concept you can develop android apps for online TV viewer application and online video live streaming from a valid URL containing the video.

1. Create a android project and make use of this main.xml file below.

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:orientation="vertical" >

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <VideoView
            android:id="@+id/video"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center" />
    </FrameLayout>

</LinearLayout>

2. Now construct your main activity file and make use of the below code.

MainActivity.java

public class MainActivity extends Activity {
      public static String url = "url_of_the_video_that_you_want_to_play";
      private VideoView videoView = null;
      private ProgressBar progress = null;
      private Context ctx = null;
      private MediaController mediaController = null;

     @Override
     public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setFormat(PixelFormat.TRANSLUCENT);
                setContentView(R.layout.main);
                ctx = this;
                progress = (ProgressBar) findViewById(R.id.progress);
                videoView = (VideoView) findViewById(R.id.video);
                Uri video = Uri.parse(url);
                mediaController = new MediaController(this);
                mediaController.setAnchorView(videoView);
                videoView.setMediaController(mediaController);
                videoView.setVideoURI(video);

                videoView.setOnErrorListener(new OnErrorListener() {

                               @Override
                               public boolean onError(MediaPlayer mp, int what, int extra) {
                                        // TODO Auto-generated method stub
                                        Toast.makeText(ctx, "Error occured", 500).show();
                                        return false;
                               }
                });

                videoView.setOnPreparedListener(new OnPreparedListener() {

                               public void onPrepared(MediaPlayer arg0) {
                                          progress.setVisibility(View.GONE);
                                          videoView.start();
                               }
               });
     }

     @Override
     protected void onDestroy() {
           try {
                   videoView.stopPlayback();
           } catch (Exception e) {
                   //
           }
           super.onDestroy();
     }
}

3. Add USES permission (Internet Permission) to your android manifest xml file without fail for internet access.

AndroidManifest.xml

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

Note : The video does not play in your android emulator. Just compile your code units perfectly and install the .apk file into your android device and start watching the video from the URL which you have embedded.

Read PDF files in Android Source Code

Dear all, In this post you can learn on how to read PDF files in android. Let us consider the below example that the PDF file is located in the SD card of your android phone. The below android source code example is illustrated on how to read this PDF file.

1. Create a Android Project. Download "PDFViewer.jar" and add it in the project build path. You can download the "PDFViewer.jar" from the below link.
https://github.com/jblough/Android-Pdf-Viewer-Library

2. Create an activity java file as below.

activity_second.java

public class activity_second extends PdfViewerActivity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
     // TODO Auto-generated method stub
     super.onCreate(savedInstanceState);
    }
   
    public int getPreviousPageImageResource() {
     return R.drawable.left_arrow;
    }
   
    public int getNextPageImageResource() {
     return R.drawable.right_arrow;
    }
   
    public int getZoomInImageResource() {
     return R.drawable.zoom_in;
    }
   
    public int getZoomOutImageResource() {
     return R.drawable.zoom_out;
    }
   
    public int getPdfPasswordLayoutResource() {
     return R.layout.pdf_file_password;
    }
   
    public int getPdfPageNumberResource() {
     return R.layout.dialog_pagenumber;
    }
   
    public int getPdfPasswordEditField() {
     return R.id.etPassword;
    }
   
    public int getPdfPasswordOkButton() {
     return R.id.btOK;
    }
   
    public int getPdfPasswordExitButton() {
     return R.id.btExit;
    }
   
    public int getPdfPageNumberEditField() {
     return R.id.pagenum_edit;
    }
}

3. Now add the below class into your project's main activity and extend this class to ListActivity.

activity_first.java

public class activity_first extends ListActivity {
     
    String[] pdflist;
    File[] imagelist;
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     //setContentView(R.layout.main);
   
     File images = Environment.getExternalStorageDirectory();
     imagelist = images.listFiles(new FilenameFilter() {
      public boolean accept(File dir, String name) {
       return ((name.endsWith(".pdf")));
      }
     });
     pdflist = new String[imagelist.length];
     for (int i = 0; i < imagelist.length; i++) {
      pdflist[i] = imagelist[i].getName();
     }
     this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pdflist));
    }
   
    protected void onListItemClick(ListView l, View v, int position, long id) {
     super.onListItemClick(l, v, position, id);
     String path = imagelist[(int) id].getAbsolutePath();
     openPdfIntent(path);
    }
   
    private void openPdfIntent(String path) {
     try {
      final Intent intent = new Intent(activity_first.this, Second.class);
      intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
      startActivity(intent);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
}

4. Add your Second Activity too in your Android Manifest.xml file without fail.

Check Internet Connection in Android Source Code

You can check the availability of internet connection in android device by using the following source code example. While building android web applications it is necessary to check whether the device has internet connection available or not. This concept is very important and is very useful while developing android applications for validation purposes.

Android Source Code Example to Check Internet Connectivity

1. The below main activity returns the boolean value as true if there is internet connection in the device and if it returns false then there is no internet access in the android device.

public class isNetworkAvailable {

//return boolean as true if there is internet access

 public static boolean isNetworkAvailable(Context context) {
     ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
     if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
           for (int i = 0; i < info.length; i++) {
              if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                 return true;
              }
           }
        }
     }
     return false;
  }
}

2. Please add the USES permission (Internet / Wifi) in the android manifest file.

LED Notification Android Source Code Example

This is a simple android project where you can see LED notification with different colors in the android mobile screen. Please find below the source code example. No special permissions are required for this project. Just you can run with default manifest and layout. Before seeing the demo through android IDE, just lock your phone screen to see the LED illumination.

NotificationLED.java

public class NotificationLED extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  for (int i = 0; i < 8; i++) {
   notif.cancel(1); // clear all previous notification 
   final Notification notification = new Notification();
   if (i == 0){
    notification.ledARGB = Color.MAGENTA;
   }else if (i == 1){
    notification.ledARGB = Color.BLUE;
   }else if (i == 2){
    notification.ledARGB = Color.CYAN;
   }else if (i == 3){
    notification.ledARGB = Color.GRAY;
   }else if (i == 4){
    notification.ledARGB = Color.GREEN;
   }else if (i == 5){
    notification.ledARGB = Color.RED;
   }else if (i == 6){
    notification.ledARGB = Color.WHITE;
   }else if (i == 7){
    notification.ledARGB = Color.YELLOW;
   }
   notification.ledOnMS = 1000;
   notification.flags |= Notification.FLAG_SHOW_LIGHTS;
   notif.notify(1, notification);
   try {
    Thread.sleep(2000);
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
  }

 }


My Profile