Wednesday 29 May 2013

Google analytics example

1)VideoDetailList.java
package com.app.v3;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

import android.R.array;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class VideoDetailList extends Activity implements OnClickListener{
    //private Button imgDownloadList = null;
    private String VIDEO_DOWNLOAD_LIST    = "VideoDownloadList";
    //private ImageButton imgBack = null;
    private Button btnPlay = null;
    private Button btnDownload = null;
    private String strId = null;
    private String strType = null;
    private String strTitle = null;
    private String strVideoImg = null;
    private String strVideoDescription = null;
    private String strVideoSmall = null;
    private String strVideoHD = null;
    //private TextView txtSubHeading = null;
    private TextView txtDiscription = null;
    private TextView txtTitleDiscription = null;
    private GoogleAnalytics    GA_instant = null;
    private Tracker    tracker    = null;
    private Button btnBack = null;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xdetaillist);
       
        strId = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_ID);
        strType = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_VIDEO_TYPE);
        strTitle = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_VIDEO_TITLE);
        strVideoImg = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_VIDEO_IMG);
        strVideoDescription = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_VIDEO_DESC);
        System.out.println("Description==="+strVideoDescription);
        strVideoSmall = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_VIDEO_SMALL);
        strVideoHD = getIntent().getStringExtra(Constants.DETAIL_VIDEO_INTENT.KEY_VIDEO_HD);
       
        GA_instant = GoogleAnalytics.getInstance(this);
        tracker = GA_instant.getTracker(Constants.GOOGLE_ANALYTICS.GOOGLE_ANALYTICS_ID);
        GAServiceManager.getInstance().setDispatchPeriod(30);
        GA_instant.setDebug(true);
       
        //txtSubHeading = (TextView)findViewById(R.id.tvSubHeading);
        //txtSubHeading.setText(strTitle);
        txtDiscription = (TextView)findViewById(R.id.txtDetailDiscription);
        txtDiscription.setText(strVideoDescription);
        txtTitleDiscription = (TextView)findViewById(R.id.txtDescriptionTitle);
        txtTitleDiscription.setText(strTitle);
       
//        imgDownloadList = (Button)findViewById(R.id.ImgDownloadList);
//        imgDownloadList.setOnClickListener(new OnClickListener() {
//            public void onClick(View v) {
//                Intent mIntentDownload = new Intent(VideoDetailList.this,VideoDownloadList.class);
//                View view = ViewGroupOrganizer.group.getLocalActivityManager().startActivity(VIDEO_DOWNLOAD_LIST,mIntentDownload.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
//                ViewGroupOrganizer.group.replaceView(view);
//            }
//        });
        btnPlay = (Button)findViewById(R.id.btnPlay);
        btnPlay.setOnClickListener(this);
       
        btnDownload = (Button)findViewById(R.id.btnDownload);
        btnDownload.setOnClickListener(this);
       
        btnBack = (Button)findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        tracker.sendView("/Video Play");
    }

    public void onClick(View v) {
        if(v==btnPlay){
            PlayVideoDialog();
        }
        else if(v==btnBack){
            finish();
        }
        else if(v==btnDownload){
            boolean DownloadStatus=false;
            OpenDatabase();
              DownloadStatus=mDbHelper.SearchDuplicateDownloadVideo(mSQLiteDatabase, strId,strTitle.toString().trim());
            CloseDataBase();
       
            if(DownloadStatus){
                SearchDuplicateDialog();
                //Toast.makeText(mContext, Html.fromHtml(Constants.DOWNLOAD.RECORD_DUPLICATE_MESSAGE),Toast.LENGTH_LONG).show();
            }
            else{                           
                    if(CommanClass.isTablet(VideoDetailList.this))
                    {
                        intFileName = strVideoHD.toString().hashCode();
                        System.out.println("strFileName=="+intFileName);
                        //mPosition = position;
                        DownloadVideoDialog();
                    }
                    else{
                        intFileName = strVideoSmall.toString().hashCode();
                        System.out.println("strFileName=="+intFileName);
                        //mPosition = position;
                        DownloadVideoDialog();
                    }
            }
        }
    }
   
    //******************************************************************************************************************
//    Alert dialog for download
    private void DownloadVideoDialog(){
        AlertDialog mAlertDialog = new AlertDialog.Builder(this).create();
        mAlertDialog.setTitle(Constants.DOWNLOAD.DOWNLOAD);
        mAlertDialog.setMessage(Constants.DOWNLOAD.DOWNLOAD_MASSAGE);
        mAlertDialog.setButton(Constants.DOWNLOAD.DIALOG_BUTTON_YES, new DialogInterface.OnClickListener() {           
            public void onClick(DialogInterface dialog, int which) {   
                    if(CommanClass.isTablet(VideoDetailList.this))
                    {
                        new DownloadVideo().execute(strVideoHD.toString());
                    }
                    else
                    {
                        new DownloadVideo().execute(strVideoSmall.toString());
                    }
                    dialog.cancel();
                }
            });
            mAlertDialog.setButton2(Constants.DOWNLOAD.DIALOG_BUTTON_NO, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        mAlertDialog.show();
    }
    //******************************************************************************************************************
//    Alert dialog for download
    private void PlayVideoDialog() {
       
        AlertDialog mAlertDialog = new AlertDialog.Builder(this).create();
        mAlertDialog.setTitle(Constants.PLAY_DIALOG.PLAY_DIALOG_TITLE);
        mAlertDialog.setMessage(Constants.PLAY_DIALOG.PLAY_DIALOG_MESSAGE);
        mAlertDialog.setButton(Constants.PLAY_DIALOG.PLAY_DIALOG_BUTTON_YES, new DialogInterface.OnClickListener() {           
            public void onClick(DialogInterface dialog, int which) {   
                    tracker.sendEvent(Constants.GOOGLE_ANALYTICS.PLAY_VIDEO, Constants.GOOGLE_ANALYTICS.PLAY, Constants.GOOGLE_ANALYTICS.VIDEO_DOWNLOAD_LOG, (long) 0);
                    CheckNetworkStatus();
                    dialog.cancel();
                }
            });
            mAlertDialog.setButton2(Constants.PLAY_DIALOG.PLAY_DIALOG_BUTTON_NO, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        mAlertDialog.show();
    }
    //******************************************************************************************************************
//    Alert dialog for download
    private void INSERT_SUCCESSFULL_VIDEODIALOG() {
       
        AlertDialog mAlertDialog = new AlertDialog.Builder(this).create();
        mAlertDialog.setTitle(Constants.DOWNLOAD.VEDIO_STORE_SUCCESSFULLY_TITLE);
        mAlertDialog.setMessage(Constants.DOWNLOAD.VEDIO_STORE_SUCCESSFULLY_MESSAGE);
        mAlertDialog.setButton(Constants.DOWNLOAD.DIALOG_BUTTON_OK, new DialogInterface.OnClickListener() {           
            public void onClick(DialogInterface dialog, int which) {   
                    dialog.cancel();
                }
            });
        mAlertDialog.show();
    }
    //******************************************************************************************************************************
    //For Download Video file
        private int intFileName;
        private ProgressDialog mProgressDialog = null;
        int progress = 0;
        private class DownloadVideo extends AsyncTask<String,Integer, Boolean>{       
        boolean Status=false, inPostExecute = false;
        protected void onPreExecute() {
            Status = true;           
            mProgressDialog = new ProgressDialog(VideoDetailList.this);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMessage(Constants.DOWNLOAD.DOWNLOADING_MESSAGE);
            mProgressDialog.setOnDismissListener(new OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                    if(inPostExecute == false){
                        Status = false;
                    }
                    if (!(DownloadVideo.this.isCancelled())) {
                        DownloadVideo.this.cancel(true);
                        if(CommanClass.MemoryCardCheck() && Status == false){
                            if(new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").exists()){
                                new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").delete();
                            }
                         }
                    }
                }
            });
            mProgressDialog.show();
            //For set screen orientation
            int currentOrientation = getResources().getConfiguration().orientation;
            if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE){
               setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            }
            else{
               setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
            }           
            super.onPreExecute();
           }   
               protected Boolean doInBackground(String... MP3URL) {
                   if(CommanClass.MemoryCardCheck())
                   {     
                       int count;
                        try{
                                URL url = new URL(MP3URL[0]);
                                URLConnection conexion = url.openConnection();
                                conexion.connect();
                               
                                File VideoDirectory = new File(Constants.DOWNLOAD.SDCARD_VIDEO_URL);
                                   if(!VideoDirectory.exists()){
                                       VideoDirectory.mkdir();
                                   }   
                                   int lenghtOfFile = conexion.getContentLength();
                                    InputStream mInputStream=CommanClass.OpenHttpConnectionPost(MP3URL[0]);                                                                                                                    
                                    FileOutputStream fos = new FileOutputStream(VideoDirectory + "/video_" + intFileName+".mp4");
                                           byte data[] = new byte[1024];
                                           long total = 0;
                                           while ((count = mInputStream.read(data)) != -1 && Status) {
                                               total += count;
                                               publishProgress((int)((total*100)/lenghtOfFile));
                                               fos.write(data, 0, count);
                                           }
                                            fos.close();
                                            mInputStream.close();
                            }
                            catch (Exception e) {
                                   e.printStackTrace();
                                    Status=false;
                            }
                    }
                   else{
                          Status=false;
                   }
                   return Status;
               }
              
             /** This callback method is invoked when publishProgress()
                * method is called */
               @Override
               protected void onProgressUpdate(Integer... values) {
                   super.onProgressUpdate(values);
                   mProgressDialog.setProgress(values[0]);
               }
              
            protected void onPostExecute(Boolean result) {
                    if(result){
                            tracker.sendEvent(Constants.GOOGLE_ANALYTICS.DOWNLOAD_VIDEO,Constants.GOOGLE_ANALYTICS.DOWNLOAD, Constants.GOOGLE_ANALYTICS.VIDEO_DOWNLOAD_LOG, (long) 0);
                            inPostExecute = true;
                            Toast.makeText(VideoDetailList.this,Html.fromHtml(Constants.DOWNLOAD.DOWNLOADING_MESSAGE), Toast.LENGTH_SHORT).show();
                           
                                if(CommanClass.isTablet(VideoDetailList.this))
                                {
                                    OpenDatabase();                                     
                                        mDbHelper.INSERT_DOWNLOAD_VIDEO(mSQLiteDatabase, strId,strTitle.toString(),intFileName+".mp4",strType.toString(),strVideoImg.toString(),strVideoDescription.toString(),strVideoHD.toString());
                                        INSERT_SUCCESSFULL_VIDEODIALOG();
                                    CloseDataBase();
                                }
                                else{
                                    OpenDatabase();         
                                        mDbHelper.INSERT_DOWNLOAD_VIDEO(mSQLiteDatabase,strId,strTitle.toString(),intFileName+".mp4",strType.toString(),strVideoImg.toString(),strVideoDescription.toString(),strVideoSmall.toString());
                                        INSERT_SUCCESSFULL_VIDEODIALOG();
                                    CloseDataBase();
                                }
                               
                    }
                    else{
                         if(CommanClass.MemoryCardCheck()){
                            if(new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").exists()){
                                new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").delete();
                            }
                         }
                            Toast.makeText(VideoDetailList.this,Html.fromHtml(Constants.DOWNLOAD.NOT_DOWNLOAD), Toast.LENGTH_SHORT).show();
                    }        
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                   mProgressDialog.dismiss();
                   super.onPostExecute(result);                       
            }     
         }
           
    // For play Video on click of perticular list item   
    public void CheckNetworkStatus(){
         Intent mintent = new Intent(VideoDetailList.this, VideoPlay.class);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_ID, strId);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_VIDEO_TYPE, strType);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_VIDEO_TITLE, strTitle);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_VIDEO_IMG, strVideoImg);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_VIDEO_DESC, strVideoDescription);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_VIDEO_SMALL, strVideoSmall);
         mintent.putExtra(Constants.PLAY_VIDEO_INTENT.KEY_VIDEO_HD, strVideoHD);       
         mintent.setAction(Constants.PLAY_VIDEO.PLAY_LIST_VEDIO);
       
                final ConnectivityManager mConnectivityManager = (ConnectivityManager) VideoDetailList.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                if(mConnectivityManager!=null){
//                        final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//                        final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                    android.net.NetworkInfo mobile = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                    android.net.NetworkInfo wifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        if (wifi.getState() == android.net.NetworkInfo.State.CONNECTED || wifi.getState() == android.net.NetworkInfo.State.CONNECTING) {
                                if(CommanClass.isTablet(VideoDetailList.this))
                                {
                                    Log.e("log_tag=", "device is hd.");
                                    mintent.putExtra(Constants.PLAY_VIDEO.LIST_VIDEO_KEY,strVideoHD.toString());
                                    startActivity(mintent);
                                    //intent.setDataAndType(Uri.parse(anshd.get(position).toString()), "video/*");
                                }
                                else
                                {
                                    Log.e("log_tag", "device is not hd.");
                                    mintent.putExtra(Constants.PLAY_VIDEO.LIST_VIDEO_KEY, strVideoSmall.toString());
                                    startActivity(mintent);
                                    //  intent.setDataAndType(Uri.parse(ans.get(position).toString()), "video/*");
                                }
                        } else{
                            if(mobile != null){
                                if (mobile.getState() == android.net.NetworkInfo.State.CONNECTED || mobile.getState() == android.net.NetworkInfo.State.CONNECTING) {
                                    mintent.putExtra(Constants.PLAY_VIDEO.LIST_VIDEO_KEY, strVideoSmall.toString());
                                    startActivity(mintent);
                                }
                                 else {
                                        Toast.makeText(this, "Network connection is not available.", Toast.LENGTH_LONG).show();
                                 } 
                            }
                            else {
                                    Toast.makeText(this, "Network connection is not available.", Toast.LENGTH_LONG).show();
                                } 
                        }
                }
              
    }
   
    //*******************************************************************************************************************************   
    public void SearchDuplicateDialog(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder
            .setMessage(Constants.DOWNLOAD.RECORD_DUPLICATE_MESSAGE)
            .setCancelable(false)
            .setPositiveButton(Constants.WELCOME_MESSAGE.POSITIVE_BUTTON_TEXT,new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        dialog.cancel();
                    }
                  });
       
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
        }
   
    /**THIS FUNCTION IS USED FOR OPEN DATABASE    */
       private DbHelper mDbHelper=null;
      private SQLiteDatabase mSQLiteDatabase=null;   
      private void OpenDatabase()
      {   
            try{
                     if(mDbHelper==null && mSQLiteDatabase==null){
                         mDbHelper = new DbHelper(VideoDetailList.this);
                        mSQLiteDatabase = mDbHelper.getWritableDatabase();
    //                    mSQLiteDatabase.setLockingEnabled(true);
                     }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
      }

    /**THIS FUNCTION IS USED FOR CLOSE DATABASE    */
      private void CloseDataBase()
      {
          try{
                  if(mDbHelper!=null && mSQLiteDatabase!=null){
                        mSQLiteDatabase.close();
                        mDbHelper.close();
                        mSQLiteDatabase=null;
                        mDbHelper=null;
                  }
              }
              catch (Exception e) {
                e.printStackTrace();
              }
      }
}
==============================
2)constans.java
===========
public static final class GOOGLE_ANALYTICS{
        public static final String PLAY_VIDEO = "play_video";
        public static final String PLAY = "play";
        public static final String VIDEO_PLAY_LOG = "video_play_log";
        public static final String DOWNLOAD_VIDEO = "download_video";
        public static final String DOWNLOAD = "download";
        public static final String VIDEO_DOWNLOAD_LOG = "video_download_log";
        public static final String  GOOGLE_ANALYTICS_ID= "UA-1547067-53";
    }

No comments:

Post a Comment