Java tutorial
/** '********************************************************************************************************************* '* Project Name : GuardTrax '* File Name : SplashScreen.java '* Description : SplashScreen Activity of Application '* Package Name : com.guardtrax.ui.screens '* Version Number : 1.0 '* Original Author : Prasanna Vignesh R '* Start Date : 10 August 2011 '* Last Modified Date : 14 September 2011 '* Modified By : Prasanna Vignesh R '* GuardTrax, 2011, Confidential and proprietary. '********************************************************************************************************************** */ package com.guardtrax.ui.screens; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.List; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import com.guardtrax.R; import com.guardtrax.db.PreferenceDB; import com.guardtrax.util.GTConstants; import com.guardtrax.util.Utility; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Looper; import android.widget.Toast; public class SplashScreen extends Activity { // Variable declaration according to Data types boolean debug = false; PreferenceDB preferenceDB; private static LocationManager locationManagerObj; //private static LocationListener locationListnerObj; //private static GpsSats Sats; //private boolean GPSFix = false; private boolean syncComplete = false; //private Location loc; //private Location lastLocation; //private long lastTime; //private double lastSpeed; //private long elapsedTime = 30; //default to 30 so that initially the GPS will be set with some location data with a V private Dialog dialog; public static int Satellites = -1; //static long minTime = 1000; //static float minDistance = 1; static boolean gps_enabled = false; static boolean network_enabled = false; String serialNumber = ""; String androidID = ""; String serialnum = null; SyncDB syncdb = null; @Override // Called when activity starts public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //if already running then resume at the last page opened if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { // Activity was brought to front and not created, thus finishing this will get us to the last viewed activity finish(); return; } setContentView(R.layout.splashscreen); //Load the GT constants loadGTConstants(); //check directory structure checkDir(); //sync with server syncDB(); //code line below is moved into onClick above when in debug mode initialize(); } @Override public void onResume() { super.onResume(); //setVisible(true); } private void initialize() { if (locationManagerObj == null) { locationManagerObj = (LocationManager) getSystemService(Context.LOCATION_SERVICE); try { gps_enabled = locationManagerObj.isProviderEnabled(LocationManager.GPS_PROVIDER); //network_enabled = locationManagerObj.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { } } // don't start listeners if no provider is enabled - Changed to to look for both //if (!gps_enabled) if (!gps_enabled && !network_enabled) { AlertDialog.Builder dialog = new AlertDialog.Builder(SplashScreen.this); dialog.setTitle("Info"); dialog.setMessage("Please enable GPS!"); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); } }); dialog.show(); } else { Runnable showWaitDialog = new Runnable() { @Override public void run() { Looper.prepare(); int i = 0; //if syncComplete is true already it means that we are not trying to sync, hence delay so that splash screen can close slowly if (syncComplete) { try { Thread.sleep(1000); } catch (Exception e) { } } else { while (!syncComplete || i++ < 10) { try { Thread.sleep(1000); } catch (Exception e) { break; } } //make sure background task is completed. If not, force it closed if (!syncComplete) { try { if (syncdb.getStatus() != AsyncTask.Status.FINISHED) syncdb.cancel(true); } catch (Exception e) { } } } //After receiving first GPS Fix dismiss the Progress Dialog dialog.dismiss(); //calling the tab class causes the current tab to be displayed (set to tab(0) which is the HomeScreen) Intent intent = new Intent(); intent.setClass(SplashScreen.this, HomeScreen.class); startActivity(intent); //transition from splash to main menu is slowed down to a fade by this command overridePendingTransition(R.anim.activityfadein, R.anim.splashfadeout); SplashScreen.this.finish(); } }; // Create a Dialog to let the User know that we're waiting for a GPS Fix dialog = ProgressDialog.show(SplashScreen.this, "Please wait", "Initializing ...", true); Thread t = new Thread(showWaitDialog); t.start(); } } //this routine checks that the required directories exist. If not it creates them private void checkDir() { File folder = null; folder = new File(Environment.getExternalStorageDirectory().toString() + "/GT/s"); if (!folder.exists()) { folder.mkdirs(); Toast.makeText(SplashScreen.this, "GT/s Folder Created", Toast.LENGTH_LONG).show(); } folder = new File(Environment.getExternalStorageDirectory().toString() + "/GT/r"); if (!folder.exists()) { folder.mkdirs(); Toast.makeText(SplashScreen.this, "GT/r Folder Created", Toast.LENGTH_LONG).show(); } folder = new File(Environment.getExternalStorageDirectory().toString() + "/GT/sync"); if (!folder.exists()) { folder.mkdirs(); Toast.makeText(SplashScreen.this, "GT/sync Folder Created", Toast.LENGTH_LONG).show(); } folder = new File(Environment.getExternalStorageDirectory().toString() + "/GT/temp"); if (!folder.exists()) { folder.mkdirs(); Toast.makeText(SplashScreen.this, "GT/temp Folder Created", Toast.LENGTH_LONG).show(); } folder = new File(Environment.getExternalStorageDirectory().toString() + "/GT/docs"); if (!folder.exists()) { folder.mkdirs(); Toast.makeText(SplashScreen.this, "GT/doc Folder Created", Toast.LENGTH_LONG).show(); } } //allows toast message from background task private void splash_screen_toast(final String message, final boolean bshort) { SplashScreen.this.runOnUiThread(new Runnable() { public void run() { if (bshort) Toast.makeText(SplashScreen.this, message, Toast.LENGTH_SHORT).show(); else Toast.makeText(SplashScreen.this, message, Toast.LENGTH_LONG).show(); } }); } //Load the GT constants private void loadGTConstants() { //get the GT constants try { //initialize the GPS values GTConstants.locationInfoDTO.setLatitude(0); GTConstants.locationInfoDTO.setLongitude(0); GTConstants.locationInfoDTO.setGpsSpeed(0); GTConstants.locationInfoDTO.setGpsStatus("V"); preferenceDB = new PreferenceDB(SplashScreen.this); if (preferenceDB.checkDataBase()) { preferenceDB.open(); Cursor c = preferenceDB.getRecordByRowID("1"); preferenceDB.close(); GTConstants.LOCATIONUPDATESINTERVAL = c.getString(1); GTConstants.LOCATIONUPDATEDISTANCEINTERVAL = c.getString(2); GTConstants.SERVERIP = c.getString(3); GTConstants.SERVERPORT = Integer.parseInt(c.getString(4)); GTConstants.PANIC_NUMBER = c.getString(5); GTConstants.UNIQUE_ID = c.getString(6); GTConstants.ACCELEROMETER_SPEED = Integer.parseInt(c.getString(7)); GTConstants.LICENSE_ID = c.getString(8); GTConstants.PHONE_TYPE = c.getString(9); GTConstants.REGISTRATION = c.getString(10); c.close(); } } catch (Exception e) { Toast.makeText(SplashScreen.this, "error: " + e.toString(), Toast.LENGTH_SHORT).show(); } } //To Synchronize data with server private void syncDB() { //only sync registered devices, not those with dummy license if (!Utility.deviceRegistered()) { Toast.makeText(SplashScreen.this, "Device not registered!", Toast.LENGTH_LONG).show(); syncComplete = true; } else { syncdb = new SyncDB(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) syncdb.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else syncdb.execute(); } } private class SyncDB extends AsyncTask<String, Object, Boolean> { @Override //Runs on the UI thread before doInBackground(Params...). protected void onPreExecute() { Toast.makeText(SplashScreen.this, "Syncing databases", Toast.LENGTH_LONG).show(); } @Override protected void onPostExecute(Boolean newFile) { /* if(newFile) { try { //get the name of the new file List<String> sync_file = Utility.get_saved_file_names("/GT/sync", true, true, "*"); //get the data from that file String syncData = Utility.read_from_file(SplashScreen.this,sync_file.get(0)); //parse the data Utility.parse_ini(SplashScreen.this, syncData); }catch(Exception e) { Toast.makeText(SplashScreen.this, "Error: " + e, Toast.LENGTH_SHORT).show(); } } */ Toast.makeText(SplashScreen.this, "Syncing complete", Toast.LENGTH_SHORT).show(); syncComplete = true; } @Override protected Boolean doInBackground(String... params) { boolean success = false; boolean result = false; BufferedOutputStream fos = null; String get_file_name = ""; String current_file_name = ""; FTPClient ftp = new FTPClient(); try { ftp.connect(GTConstants.ftpURL); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { if (ftp.login("ftpconnect", "Renova11")) { if (debug) splash_screen_toast("Login", true); ftp.enterLocalPassiveMode(); //if needed create directory for device to device exchange for future use String directoryName = "/Android/send/" + GTConstants.LICENSE_ID.substring(7); ftp.changeWorkingDirectory(directoryName); //check if directory exists. If not create it if (ftp.getReplyCode() == 550) { if (!ftp.makeDirectory(directoryName)) if (debug) splash_screen_toast("send directory fail", true); } //create receive directory for device to device exchange directoryName = "/Android/receive/" + GTConstants.LICENSE_ID.substring(7); ftp.changeWorkingDirectory(directoryName); //check if directory exists. if (ftp.getReplyCode() == 550) { if (!ftp.makeDirectory(directoryName)) if (debug) splash_screen_toast("documents directory fail", true); } directoryName = "/Android/receive/" + GTConstants.LICENSE_ID.substring(7) + "/sync"; ftp.changeWorkingDirectory(directoryName); //check if directory exists. If not create it if (ftp.getReplyCode() == 550) { if (!ftp.makeDirectory(directoryName)) if (debug) splash_screen_toast("sync directory fail", true); } else { //get file name of the sync file FTPFile[] getFiles = ftp.listFiles(); if (getFiles.length > 0) { get_file_name = getFiles[0].getName(); //first check to see if a sync file already exists and if so, get the filename List<String> sync_file = Utility.get_saved_file_names("/GT/sync", false, true, "*"); if (!sync_file.isEmpty()) current_file_name = sync_file.get(0); if (debug) splash_screen_toast("current sync file " + current_file_name, false); if (debug) splash_screen_toast("new sync file " + get_file_name, false); if (!current_file_name.equalsIgnoreCase(get_file_name)) { //delete the old file if it exists if (current_file_name.length() > 1) { if (debug) splash_screen_toast( "deleting file " + Environment.getExternalStorageDirectory() + "/GT/sync/" + sync_file.get(0), false); Utility.delete_file(SplashScreen.this, Environment.getExternalStorageDirectory() + "/GT/sync", sync_file.get(0)); } //get contents of file File fileDownload = new File(Environment.getExternalStorageDirectory() + "/GT/sync/" + get_file_name); fileDownload.createNewFile(); fos = new BufferedOutputStream(new FileOutputStream(fileDownload)); result = ftp.retrieveFile(get_file_name, fos); if (result) { if (fos != null) fos.close(); success = true; } else success = false; } } } //now check for document files directoryName = "/Android/receive/" + GTConstants.LICENSE_ID.substring(7) + "/documents"; ftp.changeWorkingDirectory(directoryName); //check if directory exists. if (ftp.getReplyCode() == 550) { if (!ftp.makeDirectory(directoryName)) if (debug) splash_screen_toast("documents directory fail", true); } else { //directory exists so get file names FTPFile[] getFiles = ftp.listFiles(); if (getFiles.length > 0) { //loop over all files in the ftp directory for (int i = 0; i < getFiles.length; i++) { if (debug) splash_screen_toast("ftp file: " + getFiles[i].getName(), true); //get contents of file File fileDownload = new File(Environment.getExternalStorageDirectory() + "/GT/docs/" + getFiles[i].getName()); //if file does not exist then copy it in if (!fileDownload.exists()) { //splash_screen_toast(getFiles[i].getName(), true); fileDownload.createNewFile(); fos = new BufferedOutputStream(new FileOutputStream(fileDownload)); result = ftp.retrieveFile(getFiles[i].getName(), fos); if (result) { if (fos != null) fos.close(); if (debug) splash_screen_toast("file saved", true); } } } } //now clean up the local directory by deleting all files that are not on the ftp side //get all the file names splash_screen_toast("Syncing documents", true); List<String> local_file = Utility.get_saved_file_names("/GT/docs", false, true, "*"); for (int i = 0; i < local_file.size(); i++) { //splash_screen_toast("Local File: " + local_file.get(i),true); boolean match = false; //check if local file matches one on the server for (int j = 0; j < getFiles.length; j++) if (local_file.get(i).equalsIgnoreCase(getFiles[j].getName())) match = true; //if no match then delete the local file (as long as it is not an ird file) if (!local_file.get(i).endsWith("ird") && !match) Utility.delete_file(SplashScreen.this, Environment.getExternalStorageDirectory() + "/GT/docs/", local_file.get(i)); //splash_screen_toast("FTP File: " + getFiles[j].getName(),false); } } ftp.logout(); } ftp.disconnect(); if (debug) splash_screen_toast("Log out", true); } } catch (Exception e) { if (ftp.isConnected()) { try { if (debug) splash_screen_toast("error Log out", true); ftp.logout(); ftp.disconnect(); } catch (Exception ex) { } } return false; } if (success) { try { //get the name of the new file List<String> sync_file = Utility.get_saved_file_names("/GT/sync", true, true, "*"); //get the data from that file String syncData = Utility.read_from_file(SplashScreen.this, sync_file.get(0)); //parse the data Utility.parse_ini(SplashScreen.this, syncData); } catch (Exception e) { splash_screen_toast("Error: " + e, true); } } return success; } } }