Repository: flyingrub/SpeedMeter Branch: master Commit: 1cfc19af4f6c Files: 32 Total size: 75.7 KB Directory structure: gitextract_b_71vgux/ ├── .gitignore ├── LICENSE ├── README.md ├── app/ │ ├── .gitignore │ ├── app-release.apk │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── fly/ │ │ └── speedmeter/ │ │ └── grub/ │ │ ├── Data.java │ │ ├── GpsServices.java │ │ ├── MainActivity.java │ │ └── Settings.java │ └── res/ │ ├── layout/ │ │ ├── activity_main.xml │ │ └── activity_settings.xml │ ├── menu/ │ │ └── menu_main.xml │ ├── values/ │ │ ├── color.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── values-br/ │ │ └── strings.xml │ ├── values-fr/ │ │ └── strings.xml │ ├── values-sr/ │ │ └── strings.xml │ ├── values-tr/ │ │ └── strings.xml │ ├── values-w820dp/ │ │ └── dimens.xml │ └── xml/ │ └── pref_general.xml ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .gradle /local.properties .DS_Store /build # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio *.iml ## Directory-based project format: .idea/ # if you remove the above rule, at least ignore the following: # User-specific stuff: # .idea/workspace.xml # .idea/tasks.xml # .idea/dictionaries # Sensitive or high-churn files: # .idea/dataSources.ids # .idea/dataSources.xml # .idea/sqlDataSources.xml # .idea/dynamic.xml # .idea/uiDesigner.xml # Gradle: # .idea/gradle.xml # .idea/libraries # Mongo Explorer plugin: # .idea/mongoSettings.xml ## File-based project format: *.ipr *.iws ## Plugin-specific files: # IntelliJ /out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ================================================ FILE: README.md ================================================ SpeedMeter ========== Description --- This is the repo for the speedmeter android app. It can display some useful information about your route: * The actual, real-time speed * The time elapsed * How many meters or kilometers you traveled * Your maximum speed Get it on F-Droid Get it on Google Play ![alt tag](https://raw.githubusercontent.com/flyingrub/SpeedMeter/master/screen.png) ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "21.1.2" defaultConfig { applicationId "fly.speedmeter.grub" minSdkVersion 16 targetSdkVersion 22 versionCode 24 versionName "2.3.1" } lintOptions { disable 'MissingTranslation' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.melnykov:floatingactionbutton:1.3.0' compile 'com.google.code.gson:gson:+' compile 'com.github.navasmdc:MaterialDesign:1.+@aar' } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /home/fly/Android/Sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/fly/speedmeter/grub/Data.java ================================================ package fly.speedmeter.grub; /** * Created by fly on 17/04/15. */ public class Data { private boolean isRunning; private long time; private long timeStopped; private boolean isFirstTime; private double distanceM; private double curSpeed; private double maxSpeed; private OnGpsServiceUpdate onGpsServiceUpdate; public interface OnGpsServiceUpdate{ public void update(); } public void setOnGpsServiceUpdate(OnGpsServiceUpdate onGpsServiceUpdate){ this.onGpsServiceUpdate = onGpsServiceUpdate; } public void update(){ onGpsServiceUpdate.update(); } public Data() { isRunning = false; distanceM = 0; curSpeed = 0; maxSpeed = 0; timeStopped = 0; } public Data(OnGpsServiceUpdate onGpsServiceUpdate){ this(); setOnGpsServiceUpdate(onGpsServiceUpdate); } public void addDistance(double distance){ distanceM = distanceM + distance; } public double getDistance(){ return distanceM; } public double getMaxSpeed() { return maxSpeed; } public double getAverageSpeed(){ double average; String units; if (time <= 0) { average = 0.0; } else { average = (distanceM / (time / 1000.0)) * 3.6; } return average; } public double getAverageSpeedMotion(){ long motionTime = time - timeStopped; double average; String units; if (motionTime <= 0){ average = 0.0; } else { average = (distanceM / (motionTime / 1000.0)) * 3.6; } return average; } public void setCurSpeed(double curSpeed) { this.curSpeed = curSpeed; if (curSpeed > maxSpeed){ maxSpeed = curSpeed; } } public boolean isFirstTime() { return isFirstTime; } public void setFirstTime(boolean isFirstTime) { this.isFirstTime = isFirstTime; } public boolean isRunning() { return isRunning; } public void setRunning(boolean isRunning) { this.isRunning = isRunning; } public void setTimeStopped(long timeStopped) { this.timeStopped += timeStopped; } public double getCurSpeed() { return curSpeed; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } } ================================================ FILE: app/src/main/java/fly/speedmeter/grub/GpsServices.java ================================================ package fly.speedmeter.grub; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.GpsStatus; import android.location.GpsStatus.Listener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.util.Log; public class GpsServices extends Service implements LocationListener, GpsStatus.Listener { private LocationManager mLocationManager; Location lastlocation = new Location("last"); Data data; double currentLon=0 ; double currentLat=0 ; double lastLon = 0; double lastLat = 0; PendingIntent contentIntent; @Override public void onCreate() { Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, 0); updateNotification(false); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mLocationManager.addGpsStatusListener( this); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this); } @Override public void onLocationChanged(Location location) { data = MainActivity.getData(); if (data.isRunning()){ currentLat = location.getLatitude(); currentLon = location.getLongitude(); if (data.isFirstTime()){ lastLat = currentLat; lastLon = currentLon; data.setFirstTime(false); } lastlocation.setLatitude(lastLat); lastlocation.setLongitude(lastLon); double distance = lastlocation.distanceTo(location); if (location.getAccuracy() < distance){ data.addDistance(distance); lastLat = currentLat; lastLon = currentLon; } if (location.hasSpeed()) { data.setCurSpeed(location.getSpeed() * 3.6); if(location.getSpeed() == 0){ new isStillStopped().execute(); } } data.update(); updateNotification(true); } } public void updateNotification(boolean asData){ Notification.Builder builder = new Notification.Builder(getBaseContext()) .setContentTitle(getString(R.string.running)) .setSmallIcon(R.drawable.ic_notification) .setContentIntent(contentIntent); if(asData){ builder.setContentText(String.format(getString(R.string.notification), data.getMaxSpeed(), data.getDistance())); }else{ builder.setContentText(String.format(getString(R.string.notification), '-', '-')); } Notification notification = builder.build(); startForeground(R.string.noti_id, notification); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // If we get killed, after returning from here, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } /* Remove the locationlistener updates when Services is stopped */ @Override public void onDestroy() { mLocationManager.removeUpdates(this); mLocationManager.removeGpsStatusListener(this); stopForeground(true); } @Override public void onGpsStatusChanged(int event) {} @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} class isStillStopped extends AsyncTask { int timer = 0; @Override protected String doInBackground(Void... unused) { try { while (data.getCurSpeed() == 0) { Thread.sleep(1000); timer++; } } catch (InterruptedException t) { return ("The sleep operation failed"); } return ("return object when task is finished"); } @Override protected void onPostExecute(String message) { data.setTimeStopped(timer); } } } ================================================ FILE: app/src/main/java/fly/speedmeter/grub/MainActivity.java ================================================ package fly.speedmeter.grub; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.SpannableString; import android.text.style.RelativeSizeSpan; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Chronometer; import android.widget.TextView; import android.widget.Toast; import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; import com.gc.materialdesign.widgets.Dialog; import com.google.gson.Gson; import com.melnykov.fab.FloatingActionButton; import java.util.Locale; public class MainActivity extends ActionBarActivity implements LocationListener, GpsStatus.Listener { private SharedPreferences sharedPreferences; private LocationManager mLocationManager; private static Data data; private Toolbar toolbar; private FloatingActionButton fab; private FloatingActionButton refresh; private ProgressBarCircularIndeterminate progressBarCircularIndeterminate; private TextView satellite; private TextView status; private TextView accuracy; private TextView currentSpeed; private TextView maxSpeed; private TextView averageSpeed; private TextView distance; private Chronometer time; private Data.OnGpsServiceUpdate onGpsServiceUpdate; private boolean firstfix; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); data = new Data(onGpsServiceUpdate); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //setTitle(""); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setVisibility(View.INVISIBLE); refresh = (FloatingActionButton) findViewById(R.id.refresh); refresh.setVisibility(View.INVISIBLE); onGpsServiceUpdate = new Data.OnGpsServiceUpdate() { @Override public void update() { double maxSpeedTemp = data.getMaxSpeed(); double distanceTemp = data.getDistance(); double averageTemp; if (sharedPreferences.getBoolean("auto_average", false)){ averageTemp = data.getAverageSpeedMotion(); }else{ averageTemp = data.getAverageSpeed(); } String speedUnits; String distanceUnits; if (sharedPreferences.getBoolean("miles_per_hour", false)) { maxSpeedTemp *= 0.62137119; distanceTemp = distanceTemp / 1000.0 * 0.62137119; averageTemp *= 0.62137119; speedUnits = "mi/h"; distanceUnits = "mi"; } else { speedUnits = "km/h"; if (distanceTemp <= 1000.0) { distanceUnits = "m"; } else { distanceTemp /= 1000.0; distanceUnits = "km"; } } SpannableString s = new SpannableString(String.format("%.0f %s", maxSpeedTemp, speedUnits)); s.setSpan(new RelativeSizeSpan(0.5f), s.length() - speedUnits.length() - 1, s.length(), 0); maxSpeed.setText(s); s = new SpannableString(String.format("%.0f %s", averageTemp, speedUnits)); s.setSpan(new RelativeSizeSpan(0.5f), s.length() - speedUnits.length() - 1, s.length(), 0); averageSpeed.setText(s); s = new SpannableString(String.format("%.3f %s", distanceTemp, distanceUnits)); s.setSpan(new RelativeSizeSpan(0.5f), s.length() - distanceUnits.length() - 1, s.length(), 0); distance.setText(s); } }; mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); satellite = (TextView) findViewById(R.id.satellite); status = (TextView) findViewById(R.id.status); accuracy = (TextView) findViewById(R.id.accuracy); maxSpeed = (TextView) findViewById(R.id.maxSpeed); averageSpeed = (TextView) findViewById(R.id.averageSpeed); distance = (TextView) findViewById(R.id.distance); time = (Chronometer) findViewById(R.id.time); currentSpeed = (TextView) findViewById(R.id.currentSpeed); progressBarCircularIndeterminate = (ProgressBarCircularIndeterminate) findViewById(R.id.progressBarCircularIndeterminate); time.setText("00:00:00"); time.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { boolean isPair = true; @Override public void onChronometerTick(Chronometer chrono) { long time; if(data.isRunning()){ time= SystemClock.elapsedRealtime() - chrono.getBase(); data.setTime(time); }else{ time = data.getTime(); } int h = (int)(time /3600000); int m = (int)(time - h*3600000)/60000; int s= (int)(time - h*3600000 - m*60000)/1000 ; String hh = h < 10 ? "0"+h: h+""; String mm = m < 10 ? "0"+m: m+""; String ss = s < 10 ? "0"+s: s+""; chrono.setText(hh+":"+mm+":"+ss); if (data.isRunning()){ chrono.setText(hh+":"+mm+":"+ss); } else { if (isPair) { isPair = false; chrono.setText(hh+":"+mm+":"+ss); }else{ isPair = true; chrono.setText(""); } } } }); } public void onFabClick(View v){ if (!data.isRunning()) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_pause)); data.setRunning(true); time.setBase(SystemClock.elapsedRealtime() - data.getTime()); time.start(); data.setFirstTime(true); startService(new Intent(getBaseContext(), GpsServices.class)); refresh.setVisibility(View.INVISIBLE); }else{ fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_play)); data.setRunning(false); status.setText(""); stopService(new Intent(getBaseContext(), GpsServices.class)); refresh.setVisibility(View.VISIBLE); } } public void onRefreshClick(View v){ resetData(); stopService(new Intent(getBaseContext(), GpsServices.class)); } @Override protected void onResume() { super.onResume(); firstfix = true; if (!data.isRunning()){ Gson gson = new Gson(); String json = sharedPreferences.getString("data", ""); data = gson.fromJson(json, Data.class); } if (data == null){ data = new Data(onGpsServiceUpdate); }else{ data.setOnGpsServiceUpdate(onGpsServiceUpdate); } if (mLocationManager.getAllProviders().indexOf(LocationManager.GPS_PROVIDER) >= 0) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this); } else { Log.w("MainActivity", "No GPS location provider found. GPS data display will not be available."); } if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { showGpsDisabledDialog(); } mLocationManager.addGpsStatusListener(this); } @Override protected void onPause() { super.onPause(); mLocationManager.removeUpdates(this); mLocationManager.removeGpsStatusListener(this); SharedPreferences.Editor prefsEditor = sharedPreferences.edit(); Gson gson = new Gson(); String json = gson.toJson(data); prefsEditor.putString("data", json); prefsEditor.commit(); } @Override public void onDestroy(){ super.onDestroy(); stopService(new Intent(getBaseContext(), GpsServices.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, Settings.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onLocationChanged(Location location) { if (location.hasAccuracy()) { double acc = location.getAccuracy(); String units; if (sharedPreferences.getBoolean("miles_per_hour", false)) { units = "ft"; acc *= 3.28084; } else { units = "m"; } SpannableString s = new SpannableString(String.format("%.0f %s", acc, units)); s.setSpan(new RelativeSizeSpan(0.75f), s.length()-units.length()-1, s.length(), 0); accuracy.setText(s); if (firstfix){ status.setText(""); fab.setVisibility(View.VISIBLE); if (!data.isRunning() && !TextUtils.isEmpty(maxSpeed.getText())) { refresh.setVisibility(View.VISIBLE); } firstfix = false; } }else{ firstfix = true; } if (location.hasSpeed()) { progressBarCircularIndeterminate.setVisibility(View.GONE); double speed = location.getSpeed() * 3.6; String units; if (sharedPreferences.getBoolean("miles_per_hour", false)) { // Convert to MPH speed *= 0.62137119; units = "mi/h"; } else { units = "km/h"; } SpannableString s = new SpannableString(String.format(Locale.ENGLISH, "%.0f %s", speed, units)); s.setSpan(new RelativeSizeSpan(0.25f), s.length()-units.length()-1, s.length(), 0); currentSpeed.setText(s); } } @Override public void onGpsStatusChanged (int event) { switch (event) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: GpsStatus gpsStatus = mLocationManager.getGpsStatus(null); int satsInView = 0; int satsUsed = 0; Iterable sats = gpsStatus.getSatellites(); for (GpsSatellite sat : sats) { satsInView++; if (sat.usedInFix()) { satsUsed++; } } satellite.setText(String.valueOf(satsUsed) + "/" + String.valueOf(satsInView)); if (satsUsed == 0) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_play)); data.setRunning(false); status.setText(""); stopService(new Intent(getBaseContext(), GpsServices.class)); fab.setVisibility(View.INVISIBLE); refresh.setVisibility(View.INVISIBLE); accuracy.setText(""); status.setText(getResources().getString(R.string.waiting_for_fix)); firstfix = true; } break; case GpsStatus.GPS_EVENT_STOPPED: if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { showGpsDisabledDialog(); } break; case GpsStatus.GPS_EVENT_FIRST_FIX: break; } } public void showGpsDisabledDialog(){ Dialog dialog = new Dialog(this, getResources().getString(R.string.gps_disabled), getResources().getString(R.string.please_enable_gps)); dialog.setOnAcceptButtonClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS")); } }); dialog.show(); } public void resetData(){ fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_play)); refresh.setVisibility(View.INVISIBLE); time.stop(); maxSpeed.setText(""); averageSpeed.setText(""); distance.setText(""); time.setText("00:00:00"); data = new Data(onGpsServiceUpdate); } public static Data getData() { return data; } @Override public void onBackPressed(){ Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } @Override public void onStatusChanged(String s, int i, Bundle bundle) {} @Override public void onProviderEnabled(String s) {} @Override public void onProviderDisabled(String s) {} } ================================================ FILE: app/src/main/java/fly/speedmeter/grub/Settings.java ================================================ package fly.speedmeter.grub; import android.content.BroadcastReceiver; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceGroup; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; /** * Created by fly on 19/04/15. */ public class Settings extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.settingstoolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Display the fragment as the main content. getFragmentManager() .beginTransaction() .replace(R.id.content_frame, new SettingsFragment()) .commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_general); for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) { Preference preference = getPreferenceScreen().getPreference(i); if (preference instanceof PreferenceGroup) { PreferenceGroup preferenceGroup = (PreferenceGroup) preference; for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) { updatePreference(preferenceGroup.getPreference(j)); } } else { updatePreference(preference); } } } private void updatePreference(Preference preference) { if (preference.getKey().equals("version")) { preference.setSummary(String.format("v%s (%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)); } } } } ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_settings.xml ================================================ ================================================ FILE: app/src/main/res/menu/menu_main.xml ================================================ ================================================ FILE: app/src/main/res/values/color.xml ================================================ #E0E0E0 #9E9E9E #424242 #F44336 #D32F2F #03A9F4 #1E88E5 #01579B #FFF ================================================ FILE: app/src/main/res/values/dimens.xml ================================================ 16dp 16dp ================================================ FILE: app/src/main/res/values/strings.xml ================================================ Speedmeter Max Speed Average Speed Distance Time Accuracy Satellites Waiting for GPS fix … GPS disabled In order to use this app you need the GPS to be enabled. Route in process… Max Speed : %1$s, Distance : %2$s. Settings About this app Automatically detect stop time. The time spent at stop will not count in the average speed. Use miles per hour Display the speed in mi/h instead of km/h License Donate Click in order to support my work :) … GitHub Access to the source code. Speedmeter Version Speedmeterisanid https://github.com/flyingrub/SpeedMeter GNU General Public License 2 https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6DE8SFMJKRVK2 ================================================ FILE: app/src/main/res/values/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-br/strings.xml ================================================ Speedmeter Velocidade Máxima Velocidade Média Distância Tempo Precisão Satélites Aguardando ajuste do GPS … GPS desabilitado Para utilizar este aplicativo, é necessário que o GPS esteja habilitado. Rota em processo… Velocidade Máx : %1$s, Distância : %2$s. Configurações Sobre este app Detectar automaticamente tempo de parada. O tempo gasto na parada não conta na velocidade média. Usar milhas por hora Mostrar a velocidade em mi/h ao invés de km/h Licença Doar Clique para apoiar meu trabalho :) … GitHub Acesso ao código fonte. Versão do Speedmeter Speedmeterisanid https://github.com/flyingrub/SpeedMeter GNU General Public License 2 https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6DE8SFMJKRVK2 ================================================ FILE: app/src/main/res/values-fr/strings.xml ================================================ Speedmeter Vitesse Max Vitesse Moyenne Distance Tempsime Précision Satellites En attente de localisation GPS… GPS désactivé Pour utiliser cette application, le GPS doit être activé. Parcours en cours… Vitesse Max : %1$s, Distance : %2$s. Paramètres À propos Détecter automatiquement les temps d\'arrêt. Le temps passé à l\'arrêt ne comptera pas dans la vitesse moyenne. Utiliser les miles par heure Afficher la vitesse en mi/h au lieu de km/h Licence Faire un don Cliquez pour soutenir mon travail… :) GitHub Accès au code source. Version de Speedmeter ================================================ FILE: app/src/main/res/values-sr/strings.xml ================================================ Брзиномер Макс. брзина Просечна брзина Пређени пут Време Прецизност Сателити Чекам на ГПС… ГПС искључен Да бисте користили ову апликацију морате укључити ГПС. Мерење у току… Макс. брзина: %1$s, пређени пут: %2$s. Поставке О програму Аутоматско откривање заустављања. Време проведено у стајању се не узима у обрачун просечне брзине. Лиценца Донације Подржите мој рад :) … Гитхаб Приступ изворном кôду. Издање Брзиномера ================================================ FILE: app/src/main/res/values-tr/strings.xml ================================================ Speedmeter En Yüksek Hız Ortalama Hız Mesafe Zaman Hassasiyet Kullanılan Uydular Konum Sinyali Alınıyor… Konum Devre Dışı Uygulamayı Kullanmak İçin Konumunuz Açık Olmalı. Rota Hesaplanıyor… En Yüksek Hız : %1$s, Mesafe : %2$s. Ayarlar Uygulama Hakkında Durma anını otomatik olarak algıla Hareketsiz zamanda geçen süre ortalama hıza katılmaz. Mil/saat olarak hesapla Hızı km/s yerine mil/s olarak hesaplar. Lisans Bağış Desteklemek için tıkla :) … GitHub Kaynak koduna buradan ulaşabilirsin. Uygulama Sürümü ================================================ FILE: app/src/main/res/values-w820dp/dimens.xml ================================================ 64dp ================================================ FILE: app/src/main/res/xml/pref_general.xml ================================================ ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Wed Feb 08 16:42:36 CET 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ include ':app'