diff options
author | jandegr <jandegr@users.noreply.github.com> | 2018-05-15 11:24:57 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-05-15 11:24:57 +0200 |
commit | 6164a040b89daabcef04427d566ab11064e8f8a3 (patch) | |
tree | de248409e574d5e71057350617ad121a817305c2 | |
parent | 61fc971909c28bc39b5bae78831779ae1649651b (diff) | |
download | navit-6164a040b89daabcef04427d566ab11064e8f8a3.tar.gz |
convert tabs to spaces in java files
8 files changed, 770 insertions, 770 deletions
diff --git a/navit/android/src/org/navitproject/navit/FileBrowserActivity.java b/navit/android/src/org/navitproject/navit/FileBrowserActivity.java index d24be64e3..7bd17484d 100644 --- a/navit/android/src/org/navitproject/navit/FileBrowserActivity.java +++ b/navit/android/src/org/navitproject/navit/FileBrowserActivity.java @@ -2,7 +2,7 @@ package org.navitproject.navit; //Heavily based on code from //https://github.com/mburman/Android-File-Explore -// Version of Aug 13, 2011 +// Version of Aug 13, 2011 //Also contributed: // Sugan Krishnan (https://github.com/rgksugan) - Jan 2013. // @@ -36,395 +36,395 @@ import android.widget.*; import org.navitproject.navit.R; public class FileBrowserActivity extends Activity { - // Intent Action Constants - public static final String INTENT_ACTION_SELECT_DIR = "ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION"; - public static final String INTENT_ACTION_SELECT_FILE = "ua.com.vassiliev.androidfilebrowser.SELECT_FILE_ACTION"; - - // Intent parameters names constants - public static final String startDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPath"; - public static final String returnDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPathRet"; - public static final String returnFileParameter = "ua.com.vassiliev.androidfilebrowser.filePathRet"; - public static final String showCannotReadParameter = "ua.com.vassiliev.androidfilebrowser.showCannotRead"; - public static final String filterExtension = "ua.com.vassiliev.androidfilebrowser.filterExtension"; - - // Stores names of traversed directories - ArrayList<String> pathDirsList = new ArrayList<String>(); - - // Check if the first level of the directory structure is the one showing - // private Boolean firstLvl = true; - - private static final String LOGTAG = "F_PATH"; - - private List<Item> fileList = new ArrayList<Item>(); - private File path = null; - private String chosenFile; - // private static final int DIALOG_LOAD_FILE = 1000; - - ArrayAdapter<Item> adapter; - - private boolean showHiddenFilesAndDirs = true; - - private boolean directoryShownIsEmpty = false; - - private String filterFileExtension = null; - - // Action constants - private static int currentAction = -1; - private static final int SELECT_DIRECTORY = 1; - private static final int SELECT_FILE = 2; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // In case of - // ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION - // Expects com.mburman.fileexplore.directoryPath parameter to - // point to the start folder. - // If empty or null, will start from SDcard root. - setContentView(R.layout.ua_com_vassiliev_filebrowser_layout); - - // Set action for this activity - Intent thisInt = this.getIntent(); - currentAction = SELECT_DIRECTORY;// This would be a default action in - // case not set by intent - if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) { - Log.d(LOGTAG, "SELECT ACTION - SELECT FILE"); - currentAction = SELECT_FILE; - } - - showHiddenFilesAndDirs = thisInt.getBooleanExtra( - showCannotReadParameter, true); - - filterFileExtension = thisInt.getStringExtra(filterExtension); - - setInitialDirectory(); - - parseDirectoryPath(); - loadFileList(); - this.createFileListAdapter(); - this.initializeButtons(); - this.initializeFileListView(); - updateCurrentDirectoryTextView(); - Log.d(LOGTAG, path.getAbsolutePath()); - } - - private void setInitialDirectory() { - Intent thisInt = this.getIntent(); - String requestedStartDir = thisInt - .getStringExtra(startDirectoryParameter); - - if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null - File tempFile = new File(requestedStartDir); - if (tempFile.isDirectory()) - this.path = tempFile; - }// if(requestedStartDir!=null - - if (this.path == null) {// No or invalid directory supplied in intent - // parameter - if (Environment.getExternalStorageDirectory().isDirectory() - && Environment.getExternalStorageDirectory().canRead()) - path = Environment.getExternalStorageDirectory(); - else - path = new File("/"); - }// if(this.path==null) {//No or invalid directory supplied in intent - // parameter - }// private void setInitialDirectory() { - - private void parseDirectoryPath() { - pathDirsList.clear(); - String pathString = path.getAbsolutePath(); - String[] parts = pathString.split("/"); - int i = 0; - while (i < parts.length) { - pathDirsList.add(parts[i]); - i++; - } - } - - private void initializeButtons() { - Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton); - upDirButton.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - Log.d(LOGTAG, "onclick for upDirButton"); - loadDirectoryUp(); - loadFileList(); - adapter.notifyDataSetChanged(); - updateCurrentDirectoryTextView(); - } - });// upDirButton.setOnClickListener( - - Button selectFolderButton = (Button) this - .findViewById(R.id.selectCurrentDirectoryButton); - if (currentAction == SELECT_DIRECTORY) { - selectFolderButton.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - Log.d(LOGTAG, "onclick for selectFolderButton"); - returnDirectoryFinishActivity(); - } - }); - } else {// if(currentAction == this.SELECT_DIRECTORY) { - selectFolderButton.setVisibility(View.GONE); - }// } else {//if(currentAction == this.SELECT_DIRECTORY) { - }// private void initializeButtons() { - - private void loadDirectoryUp() { - // present directory removed from list - String s = pathDirsList.remove(pathDirsList.size() - 1); - // path modified to exclude present directory - path = new File(path.toString().substring(0, - path.toString().lastIndexOf(s))); - fileList.clear(); - } - - private void updateCurrentDirectoryTextView() { - int i = 0; - String curDirString = ""; - while (i < pathDirsList.size()) { - curDirString += pathDirsList.get(i) + "/"; - i++; - } - if (pathDirsList.size() == 0) { - ((Button) this.findViewById(R.id.upDirectoryButton)) - .setEnabled(false); - curDirString = "/"; - } else - ((Button) this.findViewById(R.id.upDirectoryButton)) - .setEnabled(true); - long freeSpace = getFreeSpace(curDirString); - String formattedSpaceString = formatBytes(freeSpace); - if (freeSpace == 0) { - Log.d(LOGTAG, "NO FREE SPACE"); - File currentDir = new File(curDirString); - if(!currentDir.canWrite()) - formattedSpaceString = "NON Writable"; - } - - ((Button) this.findViewById(R.id.selectCurrentDirectoryButton)) - .setText("Select\n[" + formattedSpaceString - + "]"); - - ((TextView) this.findViewById(R.id.currentDirectoryTextView)) - .setText("Current directory: " + curDirString); - }// END private void updateCurrentDirectoryTextView() { - - private void showToast(String message) { - Toast.makeText(this, message, Toast.LENGTH_LONG).show(); - } - - private void initializeFileListView() { - ListView lView = (ListView) this.findViewById(R.id.fileListView); - LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( - LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); - lParam.setMargins(15, 5, 15, 5); - lView.setAdapter(this.adapter); - lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - public void onItemClick(AdapterView<?> parent, View view, - int position, long id) { - chosenFile = fileList.get(position).file; - File sel = new File(path + "/" + chosenFile); - Log.d(LOGTAG, "Clicked:" + chosenFile); - if (sel.isDirectory()) { - if (sel.canRead()) { - // Adds chosen directory to list - pathDirsList.add(chosenFile); - path = new File(sel + ""); - Log.d(LOGTAG, "Just reloading the list"); - loadFileList(); - adapter.notifyDataSetChanged(); - updateCurrentDirectoryTextView(); - Log.d(LOGTAG, path.getAbsolutePath()); - } else {// if(sel.canRead()) { - showToast("Path does not exist or cannot be read"); - }// } else {//if(sel.canRead()) { - }// if (sel.isDirectory()) { - // File picked or an empty directory message clicked - else {// if (sel.isDirectory()) { - Log.d(LOGTAG, "item clicked"); - if (!directoryShownIsEmpty) { - Log.d(LOGTAG, "File selected:" + chosenFile); - returnFileFinishActivity(sel.getAbsolutePath()); - } - }// else {//if (sel.isDirectory()) { - }// public void onClick(DialogInterface dialog, int which) { - });// lView.setOnClickListener( - }// private void initializeFileListView() { - - private void returnDirectoryFinishActivity() { - Intent retIntent = new Intent(); - retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); - this.setResult(RESULT_OK, retIntent); - this.finish(); - }// END private void returnDirectoryFinishActivity() { - - private void returnFileFinishActivity(String filePath) { - Intent retIntent = new Intent(); - retIntent.putExtra(returnFileParameter, filePath); - this.setResult(RESULT_OK, retIntent); - this.finish(); - }// END private void returnDirectoryFinishActivity() { - - private void loadFileList() { - try { - path.mkdirs(); - } catch (SecurityException e) { - Log.e(LOGTAG, "unable to write on the sd card "); - } - fileList.clear(); - - if (path.exists() && path.canRead()) { - FilenameFilter filter = new FilenameFilter() { - public boolean accept(File dir, String filename) { - File sel = new File(dir, filename); - boolean showReadableFile = showHiddenFilesAndDirs - || sel.canRead(); - // Filters based on whether the file is hidden or not - if (currentAction == SELECT_DIRECTORY) { - return (sel.isDirectory() && showReadableFile); - } - if (currentAction == SELECT_FILE) { - - // If it is a file check the extension if provided - if (sel.isFile() && filterFileExtension != null) { - return (showReadableFile && sel.getName().endsWith( - filterFileExtension)); - } - return (showReadableFile); - } - return true; - }// public boolean accept(File dir, String filename) { - };// FilenameFilter filter = new FilenameFilter() { - - String[] fList = path.list(filter); - this.directoryShownIsEmpty = false; - for (int i = 0; i < fList.length; i++) { - // Convert into file path - File sel = new File(path, fList[i]); - Log.d(LOGTAG, - "File:" + fList[i] + " readable:" - + (Boolean.valueOf(sel.canRead())).toString()); - int drawableID = R.drawable.file_icon; - boolean canRead = sel.canRead(); - // Set drawables - if (sel.isDirectory()) { - if (canRead) { - drawableID = R.drawable.folder_icon; - } else { - drawableID = R.drawable.folder_icon_light; - } - } - fileList.add(i, new Item(fList[i], drawableID, canRead)); - }// for (int i = 0; i < fList.length; i++) { - if (fileList.size() == 0) { - // Log.d(LOGTAG, "This directory is empty"); - this.directoryShownIsEmpty = true; - fileList.add(0, new Item("Directory is empty", -1, true)); - } else {// sort non empty list - Collections.sort(fileList, new ItemFileNameComparator()); - } - } else { - Log.e(LOGTAG, "path does not exist or cannot be read"); - } - // Log.d(TAG, "loadFileList finished"); - }// private void loadFileList() { - - private void createFileListAdapter() { - adapter = new ArrayAdapter<Item>(this, - android.R.layout.select_dialog_item, android.R.id.text1, - fileList) { - @Override - public View getView(int position, View convertView, ViewGroup parent) { - // creates view - View view = super.getView(position, convertView, parent); - TextView textView = (TextView) view - .findViewById(android.R.id.text1); - // put the image on the text view - int drawableID = 0; - if (fileList.get(position).icon != -1) { - // If icon == -1, then directory is empty - drawableID = fileList.get(position).icon; - } - textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, - 0, 0); - - textView.setEllipsize(null); - - // add margin between image and text (support various screen - // densities) - // int dp5 = (int) (5 * - // getResources().getDisplayMetrics().density + 0.5f); - int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); - // TODO: change next line for empty directory, so text will be - // centered - textView.setCompoundDrawablePadding(dp3); - return view; - }// public View getView(int position, View convertView, ViewGroup - };// adapter = new ArrayAdapter<Item>(this, - }// private createFileListAdapter(){ - - private class Item { - public String file; - public int icon; - public boolean canRead; - - public Item(String file, Integer icon, boolean canRead) { - this.file = file; - this.icon = icon; - } - - @Override - public String toString() { - return file; - } - }// END private class Item { - - private class ItemFileNameComparator implements Comparator<Item> { - public int compare(Item lhs, Item rhs) { - return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); - } - } - - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { - Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); - } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { - Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); - } - // Layout apparently changes itself, only have to provide good onMeasure - // in custom components - // TODO: check with keyboard - // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) - }// END public void onConfigurationChanged(Configuration newConfig) { - - public static long getFreeSpace(String path) { - StatFs stat = new StatFs(path); - long availSize = (long) stat.getAvailableBlocks() - * (long) stat.getBlockSize(); - return availSize; - }// END public static long getFreeSpace(String path) { - - public static String formatBytes(long bytes) { - // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) - String retStr = ""; - // One binary gigabyte equals 1,073,741,824 bytes. - if (bytes > 1073741824) {// Add GB - long gbs = bytes / 1073741824; - retStr += (new Long(gbs)).toString() + "GB "; - bytes = bytes - (gbs * 1073741824); - } - // One MB - 1048576 bytes - if (bytes > 1048576) {// Add GB - long mbs = bytes / 1048576; - retStr += (new Long(mbs)).toString() + "MB "; - bytes = bytes - (mbs * 1048576); - } - if (bytes > 1024) { - long kbs = bytes / 1024; - retStr += (new Long(kbs)).toString() + "KB"; - bytes = bytes - (kbs * 1024); - } else - retStr += (new Long(bytes)).toString() + " bytes"; - return retStr; - }// public static String formatBytes(long bytes){ + // Intent Action Constants + public static final String INTENT_ACTION_SELECT_DIR = "ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION"; + public static final String INTENT_ACTION_SELECT_FILE = "ua.com.vassiliev.androidfilebrowser.SELECT_FILE_ACTION"; + + // Intent parameters names constants + public static final String startDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPath"; + public static final String returnDirectoryParameter = "ua.com.vassiliev.androidfilebrowser.directoryPathRet"; + public static final String returnFileParameter = "ua.com.vassiliev.androidfilebrowser.filePathRet"; + public static final String showCannotReadParameter = "ua.com.vassiliev.androidfilebrowser.showCannotRead"; + public static final String filterExtension = "ua.com.vassiliev.androidfilebrowser.filterExtension"; + + // Stores names of traversed directories + ArrayList<String> pathDirsList = new ArrayList<String>(); + + // Check if the first level of the directory structure is the one showing + // private Boolean firstLvl = true; + + private static final String LOGTAG = "F_PATH"; + + private List<Item> fileList = new ArrayList<Item>(); + private File path = null; + private String chosenFile; + // private static final int DIALOG_LOAD_FILE = 1000; + + ArrayAdapter<Item> adapter; + + private boolean showHiddenFilesAndDirs = true; + + private boolean directoryShownIsEmpty = false; + + private String filterFileExtension = null; + + // Action constants + private static int currentAction = -1; + private static final int SELECT_DIRECTORY = 1; + private static final int SELECT_FILE = 2; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // In case of + // ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION + // Expects com.mburman.fileexplore.directoryPath parameter to + // point to the start folder. + // If empty or null, will start from SDcard root. + setContentView(R.layout.ua_com_vassiliev_filebrowser_layout); + + // Set action for this activity + Intent thisInt = this.getIntent(); + currentAction = SELECT_DIRECTORY;// This would be a default action in + // case not set by intent + if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) { + Log.d(LOGTAG, "SELECT ACTION - SELECT FILE"); + currentAction = SELECT_FILE; + } + + showHiddenFilesAndDirs = thisInt.getBooleanExtra( + showCannotReadParameter, true); + + filterFileExtension = thisInt.getStringExtra(filterExtension); + + setInitialDirectory(); + + parseDirectoryPath(); + loadFileList(); + this.createFileListAdapter(); + this.initializeButtons(); + this.initializeFileListView(); + updateCurrentDirectoryTextView(); + Log.d(LOGTAG, path.getAbsolutePath()); + } + + private void setInitialDirectory() { + Intent thisInt = this.getIntent(); + String requestedStartDir = thisInt + .getStringExtra(startDirectoryParameter); + + if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null + File tempFile = new File(requestedStartDir); + if (tempFile.isDirectory()) + this.path = tempFile; + }// if(requestedStartDir!=null + + if (this.path == null) {// No or invalid directory supplied in intent + // parameter + if (Environment.getExternalStorageDirectory().isDirectory() + && Environment.getExternalStorageDirectory().canRead()) + path = Environment.getExternalStorageDirectory(); + else + path = new File("/"); + }// if(this.path==null) {//No or invalid directory supplied in intent + // parameter + }// private void setInitialDirectory() { + + private void parseDirectoryPath() { + pathDirsList.clear(); + String pathString = path.getAbsolutePath(); + String[] parts = pathString.split("/"); + int i = 0; + while (i < parts.length) { + pathDirsList.add(parts[i]); + i++; + } + } + + private void initializeButtons() { + Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton); + upDirButton.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + Log.d(LOGTAG, "onclick for upDirButton"); + loadDirectoryUp(); + loadFileList(); + adapter.notifyDataSetChanged(); + updateCurrentDirectoryTextView(); + } + });// upDirButton.setOnClickListener( + + Button selectFolderButton = (Button) this + .findViewById(R.id.selectCurrentDirectoryButton); + if (currentAction == SELECT_DIRECTORY) { + selectFolderButton.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + Log.d(LOGTAG, "onclick for selectFolderButton"); + returnDirectoryFinishActivity(); + } + }); + } else {// if(currentAction == this.SELECT_DIRECTORY) { + selectFolderButton.setVisibility(View.GONE); + }// } else {//if(currentAction == this.SELECT_DIRECTORY) { + }// private void initializeButtons() { + + private void loadDirectoryUp() { + // present directory removed from list + String s = pathDirsList.remove(pathDirsList.size() - 1); + // path modified to exclude present directory + path = new File(path.toString().substring(0, + path.toString().lastIndexOf(s))); + fileList.clear(); + } + + private void updateCurrentDirectoryTextView() { + int i = 0; + String curDirString = ""; + while (i < pathDirsList.size()) { + curDirString += pathDirsList.get(i) + "/"; + i++; + } + if (pathDirsList.size() == 0) { + ((Button) this.findViewById(R.id.upDirectoryButton)) + .setEnabled(false); + curDirString = "/"; + } else + ((Button) this.findViewById(R.id.upDirectoryButton)) + .setEnabled(true); + long freeSpace = getFreeSpace(curDirString); + String formattedSpaceString = formatBytes(freeSpace); + if (freeSpace == 0) { + Log.d(LOGTAG, "NO FREE SPACE"); + File currentDir = new File(curDirString); + if(!currentDir.canWrite()) + formattedSpaceString = "NON Writable"; + } + + ((Button) this.findViewById(R.id.selectCurrentDirectoryButton)) + .setText("Select\n[" + formattedSpaceString + + "]"); + + ((TextView) this.findViewById(R.id.currentDirectoryTextView)) + .setText("Current directory: " + curDirString); + }// END private void updateCurrentDirectoryTextView() { + + private void showToast(String message) { + Toast.makeText(this, message, Toast.LENGTH_LONG).show(); + } + + private void initializeFileListView() { + ListView lView = (ListView) this.findViewById(R.id.fileListView); + LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams( + LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); + lParam.setMargins(15, 5, 15, 5); + lView.setAdapter(this.adapter); + lView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(AdapterView<?> parent, View view, + int position, long id) { + chosenFile = fileList.get(position).file; + File sel = new File(path + "/" + chosenFile); + Log.d(LOGTAG, "Clicked:" + chosenFile); + if (sel.isDirectory()) { + if (sel.canRead()) { + // Adds chosen directory to list + pathDirsList.add(chosenFile); + path = new File(sel + ""); + Log.d(LOGTAG, "Just reloading the list"); + loadFileList(); + adapter.notifyDataSetChanged(); + updateCurrentDirectoryTextView(); + Log.d(LOGTAG, path.getAbsolutePath()); + } else {// if(sel.canRead()) { + showToast("Path does not exist or cannot be read"); + }// } else {//if(sel.canRead()) { + }// if (sel.isDirectory()) { + // File picked or an empty directory message clicked + else {// if (sel.isDirectory()) { + Log.d(LOGTAG, "item clicked"); + if (!directoryShownIsEmpty) { + Log.d(LOGTAG, "File selected:" + chosenFile); + returnFileFinishActivity(sel.getAbsolutePath()); + } + }// else {//if (sel.isDirectory()) { + }// public void onClick(DialogInterface dialog, int which) { + });// lView.setOnClickListener( + }// private void initializeFileListView() { + + private void returnDirectoryFinishActivity() { + Intent retIntent = new Intent(); + retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath()); + this.setResult(RESULT_OK, retIntent); + this.finish(); + }// END private void returnDirectoryFinishActivity() { + + private void returnFileFinishActivity(String filePath) { + Intent retIntent = new Intent(); + retIntent.putExtra(returnFileParameter, filePath); + this.setResult(RESULT_OK, retIntent); + this.finish(); + }// END private void returnDirectoryFinishActivity() { + + private void loadFileList() { + try { + path.mkdirs(); + } catch (SecurityException e) { + Log.e(LOGTAG, "unable to write on the sd card "); + } + fileList.clear(); + + if (path.exists() && path.canRead()) { + FilenameFilter filter = new FilenameFilter() { + public boolean accept(File dir, String filename) { + File sel = new File(dir, filename); + boolean showReadableFile = showHiddenFilesAndDirs + || sel.canRead(); + // Filters based on whether the file is hidden or not + if (currentAction == SELECT_DIRECTORY) { + return (sel.isDirectory() && showReadableFile); + } + if (currentAction == SELECT_FILE) { + + // If it is a file check the extension if provided + if (sel.isFile() && filterFileExtension != null) { + return (showReadableFile && sel.getName().endsWith( + filterFileExtension)); + } + return (showReadableFile); + } + return true; + }// public boolean accept(File dir, String filename) { + };// FilenameFilter filter = new FilenameFilter() { + + String[] fList = path.list(filter); + this.directoryShownIsEmpty = false; + for (int i = 0; i < fList.length; i++) { + // Convert into file path + File sel = new File(path, fList[i]); + Log.d(LOGTAG, + "File:" + fList[i] + " readable:" + + (Boolean.valueOf(sel.canRead())).toString()); + int drawableID = R.drawable.file_icon; + boolean canRead = sel.canRead(); + // Set drawables + if (sel.isDirectory()) { + if (canRead) { + drawableID = R.drawable.folder_icon; + } else { + drawableID = R.drawable.folder_icon_light; + } + } + fileList.add(i, new Item(fList[i], drawableID, canRead)); + }// for (int i = 0; i < fList.length; i++) { + if (fileList.size() == 0) { + // Log.d(LOGTAG, "This directory is empty"); + this.directoryShownIsEmpty = true; + fileList.add(0, new Item("Directory is empty", -1, true)); + } else {// sort non empty list + Collections.sort(fileList, new ItemFileNameComparator()); + } + } else { + Log.e(LOGTAG, "path does not exist or cannot be read"); + } + // Log.d(TAG, "loadFileList finished"); + }// private void loadFileList() { + + private void createFileListAdapter() { + adapter = new ArrayAdapter<Item>(this, + android.R.layout.select_dialog_item, android.R.id.text1, + fileList) { + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // creates view + View view = super.getView(position, convertView, parent); + TextView textView = (TextView) view + .findViewById(android.R.id.text1); + // put the image on the text view + int drawableID = 0; + if (fileList.get(position).icon != -1) { + // If icon == -1, then directory is empty + drawableID = fileList.get(position).icon; + } + textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, + 0, 0); + + textView.setEllipsize(null); + + // add margin between image and text (support various screen + // densities) + // int dp5 = (int) (5 * + // getResources().getDisplayMetrics().density + 0.5f); + int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f); + // TODO: change next line for empty directory, so text will be + // centered + textView.setCompoundDrawablePadding(dp3); + return view; + }// public View getView(int position, View convertView, ViewGroup + };// adapter = new ArrayAdapter<Item>(this, + }// private createFileListAdapter(){ + + private class Item { + public String file; + public int icon; + public boolean canRead; + + public Item(String file, Integer icon, boolean canRead) { + this.file = file; + this.icon = icon; + } + + @Override + public String toString() { + return file; + } + }// END private class Item { + + private class ItemFileNameComparator implements Comparator<Item> { + public int compare(Item lhs, Item rhs) { + return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase()); + } + } + + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { + Log.d(LOGTAG, "ORIENTATION_LANDSCAPE"); + } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { + Log.d(LOGTAG, "ORIENTATION_PORTRAIT"); + } + // Layout apparently changes itself, only have to provide good onMeasure + // in custom components + // TODO: check with keyboard + // if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES) + }// END public void onConfigurationChanged(Configuration newConfig) { + + public static long getFreeSpace(String path) { + StatFs stat = new StatFs(path); + long availSize = (long) stat.getAvailableBlocks() + * (long) stat.getBlockSize(); + return availSize; + }// END public static long getFreeSpace(String path) { + + public static String formatBytes(long bytes) { + // TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes) + String retStr = ""; + // One binary gigabyte equals 1,073,741,824 bytes. + if (bytes > 1073741824) {// Add GB + long gbs = bytes / 1073741824; + retStr += (new Long(gbs)).toString() + "GB "; + bytes = bytes - (gbs * 1073741824); + } + // One MB - 1048576 bytes + if (bytes > 1048576) {// Add GB + long mbs = bytes / 1048576; + retStr += (new Long(mbs)).toString() + "MB "; + bytes = bytes - (mbs * 1048576); + } + if (bytes > 1024) { + long kbs = bytes / 1024; + retStr += (new Long(kbs)).toString() + "KB"; + bytes = bytes - (kbs * 1024); + } else + retStr += (new Long(bytes)).toString() + " bytes"; + return retStr; + }// public static String formatBytes(long bytes){ }// END public class FileBrowserActivity extends Activity { diff --git a/navit/android/src/org/navitproject/navit/NavitAppConfig.java b/navit/android/src/org/navitproject/navit/NavitAppConfig.java index 7cc5a6173..da9a66328 100755 --- a/navit/android/src/org/navitproject/navit/NavitAppConfig.java +++ b/navit/android/src/org/navitproject/navit/NavitAppConfig.java @@ -11,60 +11,60 @@ import android.content.SharedPreferences; public class NavitAppConfig extends Application { - private static final int MAX_LAST_ADDRESSES = 10; - private static final String TAG = "Navit"; - - private List<NavitAddress> mLastAddresses = null; - private int mLastAddressField; - private SharedPreferences mSettings; - - @Override - public void onCreate() { - mSettings = getSharedPreferences(Navit.NAVIT_PREFS, MODE_PRIVATE); - super.onCreate(); - } - - public List<NavitAddress> getLastAddresses() { - if (mLastAddresses == null) { - mLastAddresses = new ArrayList<NavitAddress>(); - int mLastAddressField = mSettings.getInt("LastAddress", -1); - if (mLastAddressField >= 0) { - int index = mLastAddressField; - do { - String addr_str = mSettings.getString("LastAddress_" + String.valueOf(index), ""); - - if (addr_str.length() > 0) { - mLastAddresses.add(new NavitAddress( - 1, - mSettings.getFloat("LastAddress_Lat_" + String.valueOf(index), 0), - mSettings.getFloat("LastAddress_Lon_" + String.valueOf(index), 0), - addr_str)); - } - - if (--index < 0) index = MAX_LAST_ADDRESSES - 1; - - } while (index != mLastAddressField); - } - } - return mLastAddresses; - } - - public void addLastAddress(NavitAddress newAddress) { - getLastAddresses(); - - mLastAddresses.add(newAddress); - if (mLastAddresses.size() > MAX_LAST_ADDRESSES) mLastAddresses.remove(0); - - mLastAddressField++; - if (mLastAddressField >= MAX_LAST_ADDRESSES) mLastAddressField = 0; - - SharedPreferences.Editor editSettings = mSettings.edit(); - - editSettings.putInt("LastAddress", mLastAddressField); - editSettings.putString("LastAddress_" + String.valueOf(mLastAddressField), newAddress.addr); - editSettings.putFloat("LastAddress_Lat_" + String.valueOf(mLastAddressField), newAddress.lat); - editSettings.putFloat("LastAddress_Lon_" + String.valueOf(mLastAddressField), newAddress.lon); - - editSettings.apply(); - } + private static final int MAX_LAST_ADDRESSES = 10; + private static final String TAG = "Navit"; + + private List<NavitAddress> mLastAddresses = null; + private int mLastAddressField; + private SharedPreferences mSettings; + + @Override + public void onCreate() { + mSettings = getSharedPreferences(Navit.NAVIT_PREFS, MODE_PRIVATE); + super.onCreate(); + } + + public List<NavitAddress> getLastAddresses() { + if (mLastAddresses == null) { + mLastAddresses = new ArrayList<NavitAddress>(); + int mLastAddressField = mSettings.getInt("LastAddress", -1); + if (mLastAddressField >= 0) { + int index = mLastAddressField; + do { + String addr_str = mSettings.getString("LastAddress_" + String.valueOf(index), ""); + + if (addr_str.length() > 0) { + mLastAddresses.add(new NavitAddress( + 1, + mSettings.getFloat("LastAddress_Lat_" + String.valueOf(index), 0), + mSettings.getFloat("LastAddress_Lon_" + String.valueOf(index), 0), + addr_str)); + } + + if (--index < 0) index = MAX_LAST_ADDRESSES - 1; + + } while (index != mLastAddressField); + } + } + return mLastAddresses; + } + + public void addLastAddress(NavitAddress newAddress) { + getLastAddresses(); + + mLastAddresses.add(newAddress); + if (mLastAddresses.size() > MAX_LAST_ADDRESSES) mLastAddresses.remove(0); + + mLastAddressField++; + if (mLastAddressField >= MAX_LAST_ADDRESSES) mLastAddressField = 0; + + SharedPreferences.Editor editSettings = mSettings.edit(); + + editSettings.putInt("LastAddress", mLastAddressField); + editSettings.putString("LastAddress_" + String.valueOf(mLastAddressField), newAddress.addr); + editSettings.putFloat("LastAddress_Lat_" + String.valueOf(mLastAddressField), newAddress.lat); + editSettings.putFloat("LastAddress_Lon_" + String.valueOf(mLastAddressField), newAddress.lon); + + editSettings.apply(); + } } diff --git a/navit/android/src/org/navitproject/navit/NavitCamera.java b/navit/android/src/org/navitproject/navit/NavitCamera.java index bd78b36b2..d3a923077 100644 --- a/navit/android/src/org/navitproject/navit/NavitCamera.java +++ b/navit/android/src/org/navitproject/navit/NavitCamera.java @@ -27,35 +27,35 @@ import android.view.SurfaceView; public class NavitCamera extends SurfaceView implements SurfaceHolder.Callback { - SurfaceHolder mHolder; - Camera mCamera; + SurfaceHolder mHolder; + Camera mCamera; - NavitCamera(Context context) - { - super(context); - mHolder = getHolder(); + NavitCamera(Context context) + { + super(context); + mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); - Log.e("NavitCamera","Creator"); + Log.e("NavitCamera","Creator"); - - } + + } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw. try { - mCamera = Camera.open(); + mCamera = Camera.open(); mCamera.setPreviewDisplay(holder); } catch (IOException exception) { mCamera.release(); mCamera = null; // TODO: add more exception handling logic here } - Log.e("NavitCamera","surfaceCreated"); + Log.e("NavitCamera","surfaceCreated"); } public void surfaceDestroyed(SurfaceHolder holder) { @@ -64,13 +64,13 @@ public class NavitCamera extends SurfaceView implements SurfaceHolder.Callback { // important to release it when the activity is paused. mCamera.stopPreview(); mCamera = null; - Log.e("NavitCamera","surfaceDestroyed"); + Log.e("NavitCamera","surfaceDestroyed"); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. - Log.e("NavitCamera","surfaceChanged "+w+"x"+h); + Log.e("NavitCamera","surfaceChanged "+w+"x"+h); mCamera.stopPreview(); Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(w, h); diff --git a/navit/android/src/org/navitproject/navit/NavitMap.java b/navit/android/src/org/navitproject/navit/NavitMap.java index 274cbdd8b..8ac01ec82 100644 --- a/navit/android/src/org/navitproject/navit/NavitMap.java +++ b/navit/android/src/org/navitproject/navit/NavitMap.java @@ -3,38 +3,38 @@ package org.navitproject.navit; import java.io.File; public class NavitMap { - private String fileName; - String mapName; - private String mapPath; + private String fileName; + String mapName; + private String mapPath; - NavitMap(String path, String map_file_name) { - mapPath = path; - fileName = map_file_name; - if (map_file_name.endsWith(".bin")) { - mapName = map_file_name.substring(0, map_file_name.length() - 4); - } else { - mapName = map_file_name; - } - } + NavitMap(String path, String map_file_name) { + mapPath = path; + fileName = map_file_name; + if (map_file_name.endsWith(".bin")) { + mapName = map_file_name.substring(0, map_file_name.length() - 4); + } else { + mapName = map_file_name; + } + } - NavitMap(String map_location) { - File mapFile = new File(map_location); - - mapPath = mapFile.getParent() + "/"; - fileName = mapFile.getName(); - if (fileName.endsWith(".bin")) { - mapName = fileName.substring(0, fileName.length() - 4); - } else { - mapName = fileName; - } - } + NavitMap(String map_location) { + File mapFile = new File(map_location); + + mapPath = mapFile.getParent() + "/"; + fileName = mapFile.getName(); + if (fileName.endsWith(".bin")) { + mapName = fileName.substring(0, fileName.length() - 4); + } else { + mapName = fileName; + } + } - public long size() { - File map_file = new File(mapPath + fileName); - return map_file.length(); - } + public long size() { + File map_file = new File(mapPath + fileName); + return map_file.length(); + } - public String getLocation() { - return mapPath + fileName; - } + public String getLocation() { + return mapPath + fileName; + } } diff --git a/navit/android/src/org/navitproject/navit/NavitSensors.java b/navit/android/src/org/navitproject/navit/NavitSensors.java index b263ed082..4b97e33b4 100644 --- a/navit/android/src/org/navitproject/navit/NavitSensors.java +++ b/navit/android/src/org/navitproject/navit/NavitSensors.java @@ -24,29 +24,29 @@ import android.hardware.SensorManager; public class NavitSensors implements SensorEventListener { - private SensorManager mSensorManager; - private int callbackid; - public native void SensorCallback(int id, int sensor, float x, float y, float z); - - - NavitSensors(Context context, int cbid) - { - mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - mSensorManager.registerListener((SensorEventListener)this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); - mSensorManager.registerListener((SensorEventListener)this, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); - callbackid=cbid; - } - - public void - onAccuracyChanged(Sensor sensor, int accuracy) - { - } - - public void - onSensorChanged(SensorEvent sev) - { - // Log.e("NavitSensor","Type:" + sev.sensor.getType() + " X:" + sev.values[0] + " Y:"+sev.values[1]+" Z:"+sev.values[2]); - SensorCallback(callbackid, sev.sensor.getType(), sev.values[0], sev.values[1], sev.values[2]); - } + private SensorManager mSensorManager; + private int callbackid; + public native void SensorCallback(int id, int sensor, float x, float y, float z); + + + NavitSensors(Context context, int cbid) + { + mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); + mSensorManager.registerListener((SensorEventListener)this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); + mSensorManager.registerListener((SensorEventListener)this, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); + callbackid=cbid; + } + + public void + onAccuracyChanged(Sensor sensor, int accuracy) + { + } + + public void + onSensorChanged(SensorEvent sev) + { + // Log.e("NavitSensor","Type:" + sev.sensor.getType() + " X:" + sev.values[0] + " Y:"+sev.values[1]+" Z:"+sev.values[2]); + SensorCallback(callbackid, sev.sensor.getType(), sev.values[0], sev.values[1], sev.values[2]); + } } diff --git a/navit/android/src/org/navitproject/navit/NavitTimeout.java b/navit/android/src/org/navitproject/navit/NavitTimeout.java index b70d8a1ad..3f6f2df63 100644 --- a/navit/android/src/org/navitproject/navit/NavitTimeout.java +++ b/navit/android/src/org/navitproject/navit/NavitTimeout.java @@ -26,33 +26,33 @@ import android.util.Log; public class NavitTimeout implements Runnable { - private static Handler handler =new Handler() { - public void handleMessage(Message m) { - Log.e("Navit","Handler received message"); - } - }; - private boolean event_multi; - private int event_callbackid; - private int event_timeout; - public native void TimeoutCallback(int id); + private static Handler handler =new Handler() { + public void handleMessage(Message m) { + Log.e("Navit","Handler received message"); + } + }; + private boolean event_multi; + private int event_callbackid; + private int event_timeout; + public native void TimeoutCallback(int id); - NavitTimeout(int timeout, boolean multi, int callbackid) - { - event_timeout=timeout; - event_multi=multi; - event_callbackid=callbackid; - handler.postDelayed(this, event_timeout); - } - public void run() { - // Log.e("Navit","Handle Event"); - if (event_multi) { - handler.postDelayed(this, event_timeout); - } - TimeoutCallback(event_callbackid); - } - public void remove() - { - handler.removeCallbacks(this); - } + NavitTimeout(int timeout, boolean multi, int callbackid) + { + event_timeout=timeout; + event_multi=multi; + event_callbackid=callbackid; + handler.postDelayed(this, event_timeout); + } + public void run() { + // Log.e("Navit","Handle Event"); + if (event_multi) { + handler.postDelayed(this, event_timeout); + } + TimeoutCallback(event_callbackid); + } + public void remove() + { + handler.removeCallbacks(this); + } } diff --git a/navit/android/src/org/navitproject/navit/NavitVehicle.java b/navit/android/src/org/navitproject/navit/NavitVehicle.java index 583d044c1..7bb0f8938 100644 --- a/navit/android/src/org/navitproject/navit/NavitVehicle.java +++ b/navit/android/src/org/navitproject/navit/NavitVehicle.java @@ -38,161 +38,161 @@ import android.support.v4.content.ContextCompat; public class NavitVehicle { - - private static final String GPS_FIX_CHANGE = "android.location.GPS_FIX_CHANGE"; - - public static Location lastLocation = null; - - private static LocationManager sLocationManager = null; - private static Context context = null; - private int vehicle_pcbid; - private int vehicle_scbid; - private int vehicle_fcbid; - private String preciseProvider; - private String fastProvider; - - private static NavitLocationListener preciseLocationListener = null; - private static NavitLocationListener fastLocationListener = null; - - public native void VehicleCallback(int id, Location location); - public native void VehicleCallback(int id, int satsInView, int satsUsed); - public native void VehicleCallback(int id, int enabled); - - private class NavitLocationListener extends BroadcastReceiver implements GpsStatus.Listener, LocationListener { - public boolean precise = false; - public void onLocationChanged(Location location) { - lastLocation = location; - // Disable the fast provider if still active - if (precise && fastProvider != null) { - sLocationManager.removeUpdates(fastLocationListener); - fastProvider = null; - } - - VehicleCallback(vehicle_pcbid, location); - VehicleCallback(vehicle_fcbid, 1); - } - public void onProviderDisabled(String provider){} - public void onProviderEnabled(String provider) {} - public void onStatusChanged(String provider, int status, Bundle extras) {} - - /** - * Called when the status of the GPS changes. - */ - public void onGpsStatusChanged (int event) { - if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) - != PackageManager.PERMISSION_GRANTED) { - // Permission is not granted - return; - } - GpsStatus status = sLocationManager.getGpsStatus(null); - int satsInView = 0; - int satsUsed = 0; - Iterable<GpsSatellite> sats = status.getSatellites(); - for (GpsSatellite sat : sats) { - satsInView++; - if (sat.usedInFix()) { - satsUsed++; - } - } - VehicleCallback(vehicle_scbid, satsInView, satsUsed); - } - - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(GPS_FIX_CHANGE)) { - if (intent.getBooleanExtra("enabled", false)) - VehicleCallback(vehicle_fcbid, 1); - else if (!intent.getBooleanExtra("enabled", true)) - VehicleCallback(vehicle_fcbid, 0); - } - } - } - - /** - * @brief Creates a new {@code NavitVehicle} - * - * @param context - * @param pcbid The address of the position callback function which will be called when a location update is received - * @param scbid The address of the status callback function which will be called when a status update is received - * @param fcbid The address of the fix callback function which will be called when a - * {@code android.location.GPS_FIX_CHANGE} is received, indicating a change in GPS fix status - */ - NavitVehicle (Context context, int pcbid, int scbid, int fcbid) { - if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) - != PackageManager.PERMISSION_GRANTED) { - // Permission is not granted - return; - } - this.context = context; - sLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); - preciseLocationListener = new NavitLocationListener(); - preciseLocationListener.precise = true; - fastLocationListener = new NavitLocationListener(); - - /* Use 2 LocationProviders, one precise (usually GPS), and one - not so precise, but possible faster. The fast provider is - disabled when the precise provider gets its first fix. */ - - // Selection criteria for the precise provider - Criteria highCriteria = new Criteria(); - highCriteria.setAccuracy(Criteria.ACCURACY_FINE); - highCriteria.setAltitudeRequired(true); - highCriteria.setBearingRequired(true); - highCriteria.setCostAllowed(true); - highCriteria.setPowerRequirement(Criteria.POWER_HIGH); - - // Selection criteria for the fast provider - Criteria lowCriteria = new Criteria(); - lowCriteria.setAccuracy(Criteria.ACCURACY_COARSE); - lowCriteria.setAltitudeRequired(false); - lowCriteria.setBearingRequired(false); - lowCriteria.setCostAllowed(true); - lowCriteria.setPowerRequirement(Criteria.POWER_HIGH); - - Log.e("NavitVehicle", "Providers " + sLocationManager.getAllProviders()); - - preciseProvider = sLocationManager.getBestProvider(highCriteria, false); - Log.e("NavitVehicle", "Precise Provider " + preciseProvider); - fastProvider = sLocationManager.getBestProvider(lowCriteria, false); - Log.e("NavitVehicle", "Fast Provider " + fastProvider); - vehicle_pcbid = pcbid; - vehicle_scbid = scbid; - vehicle_fcbid = fcbid; - - context.registerReceiver(preciseLocationListener, new IntentFilter(GPS_FIX_CHANGE)); - sLocationManager.requestLocationUpdates(preciseProvider, 0, 0, preciseLocationListener); - sLocationManager.addGpsStatusListener(preciseLocationListener); - - /* - * Since Android criteria have no way to specify "fast fix", lowCriteria may return the same - * provider as highCriteria, even if others are available. In this case, do not register two - * listeners for the same provider but pick the fast provider manually. (Usually there will - * only be two providers in total, which makes the choice easy.) - */ - if (fastProvider == null || preciseProvider.compareTo(fastProvider) == 0) { - List<String> fastProviderList = sLocationManager.getProviders(lowCriteria, false); - fastProvider = null; - for (String fastCandidate: fastProviderList) { - if (preciseProvider.compareTo(fastCandidate) != 0) { - fastProvider = fastCandidate; - break; - } - } - } - if (fastProvider != null) { - sLocationManager.requestLocationUpdates(fastProvider, 0, 0, fastLocationListener); - } - } - - public static void removeListener() { - if (sLocationManager != null) { - if (preciseLocationListener != null) { - sLocationManager.removeUpdates(preciseLocationListener); - sLocationManager.removeGpsStatusListener(preciseLocationListener); - context.unregisterReceiver(preciseLocationListener); - } - if (fastLocationListener != null) sLocationManager.removeUpdates(fastLocationListener); - } - - } + + private static final String GPS_FIX_CHANGE = "android.location.GPS_FIX_CHANGE"; + + public static Location lastLocation = null; + + private static LocationManager sLocationManager = null; + private static Context context = null; + private int vehicle_pcbid; + private int vehicle_scbid; + private int vehicle_fcbid; + private String preciseProvider; + private String fastProvider; + + private static NavitLocationListener preciseLocationListener = null; + private static NavitLocationListener fastLocationListener = null; + + public native void VehicleCallback(int id, Location location); + public native void VehicleCallback(int id, int satsInView, int satsUsed); + public native void VehicleCallback(int id, int enabled); + + private class NavitLocationListener extends BroadcastReceiver implements GpsStatus.Listener, LocationListener { + public boolean precise = false; + public void onLocationChanged(Location location) { + lastLocation = location; + // Disable the fast provider if still active + if (precise && fastProvider != null) { + sLocationManager.removeUpdates(fastLocationListener); + fastProvider = null; + } + + VehicleCallback(vehicle_pcbid, location); + VehicleCallback(vehicle_fcbid, 1); + } + public void onProviderDisabled(String provider){} + public void onProviderEnabled(String provider) {} + public void onStatusChanged(String provider, int status, Bundle extras) {} + + /** + * Called when the status of the GPS changes. + */ + public void onGpsStatusChanged (int event) { + if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) + != PackageManager.PERMISSION_GRANTED) { + // Permission is not granted + return; + } + GpsStatus status = sLocationManager.getGpsStatus(null); + int satsInView = 0; + int satsUsed = 0; + Iterable<GpsSatellite> sats = status.getSatellites(); + for (GpsSatellite sat : sats) { + satsInView++; + if (sat.usedInFix()) { + satsUsed++; + } + } + VehicleCallback(vehicle_scbid, satsInView, satsUsed); + } + + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(GPS_FIX_CHANGE)) { + if (intent.getBooleanExtra("enabled", false)) + VehicleCallback(vehicle_fcbid, 1); + else if (!intent.getBooleanExtra("enabled", true)) + VehicleCallback(vehicle_fcbid, 0); + } + } + } + + /** + * @brief Creates a new {@code NavitVehicle} + * + * @param context + * @param pcbid The address of the position callback function which will be called when a location update is received + * @param scbid The address of the status callback function which will be called when a status update is received + * @param fcbid The address of the fix callback function which will be called when a + * {@code android.location.GPS_FIX_CHANGE} is received, indicating a change in GPS fix status + */ + NavitVehicle (Context context, int pcbid, int scbid, int fcbid) { + if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) + != PackageManager.PERMISSION_GRANTED) { + // Permission is not granted + return; + } + this.context = context; + sLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); + preciseLocationListener = new NavitLocationListener(); + preciseLocationListener.precise = true; + fastLocationListener = new NavitLocationListener(); + + /* Use 2 LocationProviders, one precise (usually GPS), and one + not so precise, but possible faster. The fast provider is + disabled when the precise provider gets its first fix. */ + + // Selection criteria for the precise provider + Criteria highCriteria = new Criteria(); + highCriteria.setAccuracy(Criteria.ACCURACY_FINE); + highCriteria.setAltitudeRequired(true); + highCriteria.setBearingRequired(true); + highCriteria.setCostAllowed(true); + highCriteria.setPowerRequirement(Criteria.POWER_HIGH); + + // Selection criteria for the fast provider + Criteria lowCriteria = new Criteria(); + lowCriteria.setAccuracy(Criteria.ACCURACY_COARSE); + lowCriteria.setAltitudeRequired(false); + lowCriteria.setBearingRequired(false); + lowCriteria.setCostAllowed(true); + lowCriteria.setPowerRequirement(Criteria.POWER_HIGH); + + Log.e("NavitVehicle", "Providers " + sLocationManager.getAllProviders()); + + preciseProvider = sLocationManager.getBestProvider(highCriteria, false); + Log.e("NavitVehicle", "Precise Provider " + preciseProvider); + fastProvider = sLocationManager.getBestProvider(lowCriteria, false); + Log.e("NavitVehicle", "Fast Provider " + fastProvider); + vehicle_pcbid = pcbid; + vehicle_scbid = scbid; + vehicle_fcbid = fcbid; + + context.registerReceiver(preciseLocationListener, new IntentFilter(GPS_FIX_CHANGE)); + sLocationManager.requestLocationUpdates(preciseProvider, 0, 0, preciseLocationListener); + sLocationManager.addGpsStatusListener(preciseLocationListener); + + /* + * Since Android criteria have no way to specify "fast fix", lowCriteria may return the same + * provider as highCriteria, even if others are available. In this case, do not register two + * listeners for the same provider but pick the fast provider manually. (Usually there will + * only be two providers in total, which makes the choice easy.) + */ + if (fastProvider == null || preciseProvider.compareTo(fastProvider) == 0) { + List<String> fastProviderList = sLocationManager.getProviders(lowCriteria, false); + fastProvider = null; + for (String fastCandidate: fastProviderList) { + if (preciseProvider.compareTo(fastCandidate) != 0) { + fastProvider = fastCandidate; + break; + } + } + } + if (fastProvider != null) { + sLocationManager.requestLocationUpdates(fastProvider, 0, 0, fastLocationListener); + } + } + + public static void removeListener() { + if (sLocationManager != null) { + if (preciseLocationListener != null) { + sLocationManager.removeUpdates(preciseLocationListener); + sLocationManager.removeGpsStatusListener(preciseLocationListener); + context.unregisterReceiver(preciseLocationListener); + } + if (fastLocationListener != null) sLocationManager.removeUpdates(fastLocationListener); + } + + } } diff --git a/navit/android/src/org/navitproject/navit/NavitWatch.java b/navit/android/src/org/navitproject/navit/NavitWatch.java index ebe5c8727..332aefebf 100644 --- a/navit/android/src/org/navitproject/navit/NavitWatch.java +++ b/navit/android/src/org/navitproject/navit/NavitWatch.java @@ -25,78 +25,78 @@ import android.os.Message; import android.util.Log; public class NavitWatch implements Runnable { - private Thread thread; - private static Handler handler =new Handler() { - public void handleMessage(Message m) { - Log.e("NavitWatch","Handler received message"); - } - }; - private boolean removed; - private int watch_func; - private int watch_fd; - private int watch_cond; - private int watch_callbackid; - private boolean callback_pending; - private Runnable callback_runnable; - public native void poll(int func, int fd, int cond); - public native void WatchCallback(int id); + private Thread thread; + private static Handler handler =new Handler() { + public void handleMessage(Message m) { + Log.e("NavitWatch","Handler received message"); + } + }; + private boolean removed; + private int watch_func; + private int watch_fd; + private int watch_cond; + private int watch_callbackid; + private boolean callback_pending; + private Runnable callback_runnable; + public native void poll(int func, int fd, int cond); + public native void WatchCallback(int id); - NavitWatch(int func, int fd, int cond, int callbackid) - { - // Log.e("NavitWatch","Creating new thread for "+fd+" "+cond+" from current thread " + java.lang.Thread.currentThread().getName()); - watch_func=func; - watch_fd=fd; - watch_cond=cond; - watch_callbackid=callbackid; - final NavitWatch navitwatch=this; - callback_runnable = new Runnable() { - public void run() - { - navitwatch.callback(); - } - }; - thread = new Thread(this, "poll thread"); - thread.start(); - } - public void run() - { - for (;;) { - // Log.e("NavitWatch","Polling "+watch_fd+" "+watch_cond + " from " + java.lang.Thread.currentThread().getName()); - poll(watch_func, watch_fd, watch_cond); - // Log.e("NavitWatch","poll returned"); - if (removed) - break; - callback_pending=true; - handler.post(callback_runnable); - try { - // Log.e("NavitWatch","wait"); - synchronized(this) { - if (callback_pending) - this.wait(); - } - // Log.e("NavitWatch","wait returned"); - } catch (Exception e) { - Log.e("NavitWatch","Exception "+e.getMessage()); - } - if (removed) - break; - } - } - public void callback() - { - // Log.e("NavitWatch","Calling Callback"); - if (!removed) - WatchCallback(watch_callbackid); - synchronized(this) { - callback_pending=false; - // Log.e("NavitWatch","Waking up"); - this.notify(); - } - } - public void remove() - { - removed=true; - thread.interrupt(); - } + NavitWatch(int func, int fd, int cond, int callbackid) + { + // Log.e("NavitWatch","Creating new thread for "+fd+" "+cond+" from current thread " + java.lang.Thread.currentThread().getName()); + watch_func=func; + watch_fd=fd; + watch_cond=cond; + watch_callbackid=callbackid; + final NavitWatch navitwatch=this; + callback_runnable = new Runnable() { + public void run() + { + navitwatch.callback(); + } + }; + thread = new Thread(this, "poll thread"); + thread.start(); + } + public void run() + { + for (;;) { + // Log.e("NavitWatch","Polling "+watch_fd+" "+watch_cond + " from " + java.lang.Thread.currentThread().getName()); + poll(watch_func, watch_fd, watch_cond); + // Log.e("NavitWatch","poll returned"); + if (removed) + break; + callback_pending=true; + handler.post(callback_runnable); + try { + // Log.e("NavitWatch","wait"); + synchronized(this) { + if (callback_pending) + this.wait(); + } + // Log.e("NavitWatch","wait returned"); + } catch (Exception e) { + Log.e("NavitWatch","Exception "+e.getMessage()); + } + if (removed) + break; + } + } + public void callback() + { + // Log.e("NavitWatch","Calling Callback"); + if (!removed) + WatchCallback(watch_callbackid); + synchronized(this) { + callback_pending=false; + // Log.e("NavitWatch","Waking up"); + this.notify(); + } + } + public void remove() + { + removed=true; + thread.interrupt(); + } } |