How should I send my GPS coordinates by SMS? - android

I'm getting problems using the SmsManager to sending coordinates via SMS.
I had a problem with the transfer variables between classes, so I used Intent and Bundle, but it displays only NULL.
Does this method is wrong?
Database should I use? Please help ?
ZoltrixGPSActivity Class
package com.zoltrix.gps;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ZoltrixGPSActivity extends Activity {
TextView textLat;
TextView textLong;
TextView textAlt;
TextView textPro;
TextView textAcc;
TextView textSpeed;
public String onLocat;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.buttonExit);
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// exit
finish();
System.exit(0);
}
});
textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);
textAlt = (TextView) findViewById(R.id.textAlt);
textPro = (TextView) findViewById(R.id.textPro);
textAcc = (TextView) findViewById(R.id.textAcc);
textSpeed = (TextView) findViewById(R.id.textSpeed);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
double pLong = location.getLongitude();
double pLat = location.getLatitude();
double pAlt = location.getAltitude();
String PPro = location.getProvider();
float PAcc = location.getAccuracy();
float PSpeed = location.getSpeed();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
textAlt.setText(Double.toString(pAlt));
textPro.setText(PPro);
textAcc.setText(Float.toString(PAcc));
textSpeed.setText(Double.toString(PSpeed));
Intent i = new Intent(ZoltrixGPSActivity.this,
SendSMSActivity.class);
i.putExtra("wysokosc", pLat);
i.putExtra("speed", PSpeed);
startActivity(i);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
SendSMSActivity Class
package com.zoltrix.gps;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
public class SendSMSActivity extends Activity {
Button btnSendSMS;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
String ALT = extras.getString("wysokosc");
String SPE = extras.getString("speed");
sendSMS("510100100", "wys" + " " + ALT + " " + "spee" + " - "
+ SPE);
}
});
}
// ---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zoltrix.gps"
android:versionCode="1"
android:versionName="1.2" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.zoltrix.gps.SendSMSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.zoltrix.gps.ZoltrixGPSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

try as:
i.putExtra("wysokosc",Double.toString(pLat));
i.putExtra("speed", Float.toString(PSpeed));
instead of
i.putExtra("wysokosc", pLat);
i.putExtra("speed", PSpeed);
and declare ZoltrixGPSActivity as in manifast.xml :
<activity
android:name=".ZoltrixGPSActivity" />
instead of
<activity
android:name="com.zoltrix.gps.ZoltrixGPSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
and add these permissions also in manifast
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

you are putting double & float and taking as string from intent try to make same the both
try this way once ..
i.putExtra("wysokosc", pLat+"");
i.putExtra("speed", PSpeed+"");

Related

I can't detect the bug

This is a read/scan NFC code.
I'm trying it out and I need it to work so that I would write my own code for another read activity.
The app keeps on crashing and the error is always, "There's a bug, please fix it for the app to start."
The source video/code was this link https://www.youtube.com/watch?v=QzphwRdJ7r0
Main Activity
package com.example.nfcreadscan;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private IntentFilter[] readfilters;
private PendingIntent pendingintent;
#SuppressLint("UnspecifiedImmutableFlag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
try {
Intent intent = new Intent (this, getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingintent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter jdf = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
jdf.addDataScheme("http");
jdf.addDataAuthority("javadude.com", null);
IntentFilter jdt = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED,"text/plain");
readfilters = new IntentFilter[]{jdf, jdt};
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
processNFC(getIntent());
}
private void enableRead(){
NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this,pendingintent, readfilters,null);
}
private void disableRead(){
NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);
}
#Override
protected void onResume(){
super.onResume();
enableRead();
}
#Override
protected void onPause(){
super.onPause();
disableRead();
}
#Override
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processNFC(intent);
}
private void processNFC(Intent intent){
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
textView.setText("");
if(messages != null){
for(Parcelable message : messages){
NdefMessage ndefMessage = (NdefMessage) message;
for(NdefRecord record : ndefMessage.getRecords()) {
if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN) {
textView.append("well known: ");
if (Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
textView.append("text: ");
textView.append(new String(record.getPayload()));
textView.append("\n");
} else if (Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
textView.append("uri");
textView.append(new String(record.getPayload()));
textView.append("\n");
}
}
}
}
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nfcreadscan">
<uses-permission android:name="android.permission.NFC"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Nfcreadscan">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>

Android Service With Google Play Services Location Causing App to Open Randomly

I have a service which should capture the user's location and current battery level and send it to my firebase backend. For some reason it seems like whenever I have this service enabled in my app, my app will randomly open without any user interaction (even if the user is in another app, my app will pop open). Does anyone have any idea why this is happening?
Here is my code for the service:
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.server.converter.StringToIntConverter;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static android.R.attr.lines;
import static com.package.R.id.location;
import static com.package.R.id.view;
public class LocationBatteryService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private String currentUser;
private String city;
private String country;
private float batteryLevel;
private int batteryLevelInt;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
List<Address> addresses;
Geocoder geocoder;
#Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected synchronized void buildGoogleApiClient() {
Log.i("TAG", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String locationSyncSettings = prefs.getString("location_sync_time", "");
long intervalTime = 5;
if(locationSyncSettings.equals("5 minutes")) {
intervalTime = 5;
}
if (locationSyncSettings.equals("10 minutes")) {
intervalTime = 10;
}
if (locationSyncSettings.equals("15 minutes")) {
intervalTime = 15;
}
if (locationSyncSettings.equals("30 minutes")) {
intervalTime = 30;
}
if (locationSyncSettings.equals("1 hour")) {
intervalTime = 60;
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(TimeUnit.MINUTES.toMillis(intervalTime));
mLocationRequest.setFastestInterval(60000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i("TAG", "Connected to GoogleApiClient");
try {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
onLocationChanged(mCurrentLocation);
}
catch (SecurityException e){
Log.d("TAG", "Error: " + e);
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("TAG", "You got destoryed mate");
}
#Override
public void onLocationChanged(Location location) {
updateLocationBackend(mCurrentLocation);
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i("TAG", "Connection suspended");
mGoogleApiClient.connect();
}
public void onTaskRemoved (Intent rootIntent){
this.stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i("TAG", "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
public float getBatteryLevel() {
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
// Error checking that probably isn't needed but I added just in case.
if(level == -1 || scale == -1) {
return 50.0f;
}
return ((float)level / (float)scale) * 100.0f;
}
private void updateLocationBackend(final Location location) {
Log.i("TAG", "Location and battery being updated");
batteryLevel = getBatteryLevel();
batteryLevelInt = Math.round(batteryLevel);
// Get current user
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
currentUser = sharedPrefs.getString("Username", "");
// Get users added by you
DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(Passwords.FB_URL).child("Relations").child(currentUser);
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
for (DataSnapshot ds : dataSnapshot.getChildren()) {
final String contactNumber = ds.getKey();
// Check to see if users added you
final DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(Passwords.FB_URL).child("Contacts").child(contactNumber).child(currentUser);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child("name").exists()) {
// User has not added you so do not update location
}
// User has added you so update location
else {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean contactLocationSetting = sharedPrefs.getBoolean(contactNumber + "_location_pref", true);
Log.d("TAG", "ContactLocationSetting for " + contactNumber + " is equal to: " + contactLocationSetting);
if (location != null && contactLocationSetting == true) {
Map updateLocation = new HashMap();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
Log.e("TAG", "error is: " + e);
}
if (addresses.size() == 0) {
// Do nothing
} else {
city = addresses.get(0).getLocality();
country = addresses.get(0).getCountryName();
// String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
}
updateLocation.put("battery", batteryLevelInt);
updateLocation.put("latitude", latitude);
updateLocation.put("longitude", longitude);
updateLocation.put("city", city);
updateLocation.put("country", country);
updateLocation.put("lastUpdated", System.currentTimeMillis());
ref.updateChildren(updateLocation);
Log.d("TAG", "Updated location for: " + contactNumber);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG", "getUser:onCancelled", databaseError.toException());
}
});
}
}
Here is the code where I start the service:
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
public static ViewPager viewPager;
public static ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String currentUser = sharedPrefs.getString("Username", null);
if (currentUser == null) {
// Take user to log in screen
Log.d("TAG", "user needs to login");
Intent intent = new Intent(this, MyIntro.class);
startActivity(intent);
finish();
}
else {
// User already logged in
setupMainActivity();
}
}
#Override
public void onResume() {
super.onResume();
return;
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ChalkboardFragment(), getString(R.string.chalkboard_label));
adapter.addFragment(new ContactsFragment(), getString(R.string.contacts_label));
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChalkboardFragment();
case 1:
return new ContactsFragment();
}
return null;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setupMainActivity() {
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean locationSetting = prefs.getBoolean("location_pref", false);
Log.d("TAG", "location_pref " + locationSetting);
if (isMyServiceRunning(LocationBatteryService.class) == false && locationSetting == true) {
startService(new Intent(this, LocationBatteryService.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Application Start:
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.digits.sdk.android.Digits;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterCore;
import io.fabric.sdk.android.Fabric;
public class ApplicationStart extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this.getApplicationContext();
/*if (!FirebaseApp.getApps(this).isEmpty()) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}*/
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String currentUser = sharedPrefs.getString("Username", null);
if (currentUser == null) {
// Take user to log in screen
Log.d("TAG", "user needs to login");
Intent intent = new Intent(this, MyIntro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
// User already logged in
Log.d("TAG", "user logged in: " + currentUser);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY,TWITTER_SECRET);
Fabric.with(this, new TwitterCore(authConfig),new Digits.Builder().build());
}
public static Context getAppContext(){
return mContext;
}
}
Complete manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" android:protectionLevel="signature" />
<application android:name=".ApplicationStart" android:allowBackup="false" android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" android:supportsRtl="true" android:theme="#style/AppTheme">
<activity android:name=".MainActivity" android:label="#string/app_name" android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity" android:label="#string/title_activity_login"
android:parentActivityName=".MainActivity" />
<activity android:name=".ContactsSettingsActivity" android:label="Contact Settings"
android:launchMode="singleTop">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.ContactsChalkboard" />
</activity>
<activity android:name=".MyIntro" />
<activity android:name=".ContactsChalkboard" />
<activity android:name=".AlarmActivity" />
<activity android:name=".AddContactActivity" android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.MainActivity" />
</activity>
<activity android:name=".PictureNameActivity" android:label="#string/title_activity_picture_name"
android:parentActivityName=".LoginActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.LoginActivity" />
</activity>
<activity android:name=".Test" />
<activity android:name=".SettingsActivity" android:label="Settings">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.MainActivity" />
</activity>
<activity android:name="com.package.GeofenceActivity" android:label="#string/title_activity_geofence">
</activity>
<service android:name=".LocationBatteryService" android:enabled="true" android:exported="true" />
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".GeofenceTransitionsIntentService" />
<receiver android:name=".AlarmReceiver" android:enabled="true" android:exported="true" />
<receiver android:name=".BootReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.android.geo.API_KEY" android:value="API KEY VALUE" />
<meta-data android:name="io.fabric.ApiKey" android:value="API KEY VALUE" />
</application>
</manifest>
Well, there is no guarantee that the system keeps running your service all the time. When the application is killed, and a new location has to be delivered the play services lib will instantiate the application and start your service. You have to remove startActivity from your application class.

MapsApp that calculates distance between 2 points, Android

I would like to create an app that can calculate distance between 2 location, the first is find with GPS,while the second is set by me. The app doesn't open, and the error is in the
line 61: distance = location.distanceTo(locationSede);
Help me!
package com.example.prova.mapapplicationprove;
import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements LocationListener {
private float distance;
private float[] distfloat = new float[1];
private final LatLng POINT = new LatLng(0, 0); //longitudine e latitudine
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
LatLng sede = new LatLng(45.012447, 7.621013);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(POINT, 1));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
map.addMarker(new MarkerOptions().position(sede).title("Soluzioni"));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
if(provider != null & !provider.equals(""))
{
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(provider, 2000, 1, this);
Location locationSede = new Location("Sede");
locationSede.setLatitude(45.012447);
locationSede.setLongitude(7.621013);
distance = location.distanceTo(locationSede); //LINE NUMBER 61
// location.distanceBetween(sede.latitude,sede.longitude,location.getLatitude(),location.getLongitude(),distfloat);
if(location!=null)
{
onLocationChanged(location);
}
else{
Toast.makeText(getApplicationContext(),"Location not found, GPS disabled.",Toast.LENGTH_LONG ).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Provider is null.",Toast.LENGTH_LONG).show();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this,"Latitude: " + location.getLatitude() + "\nLongitude: " + location.getLongitude(),Toast.LENGTH_LONG ).show();
TextView textView2 = (TextView) findViewById(R.id.textview2);
TextView textView3 = (TextView) findViewById(R.id.textview3);
TextView textView4 = (TextView) findViewById(R.id.textview4);
String distanza = String.valueOf(distance);
//String distanza = String.valueOf(distfloat[0]);
textView2.setText("Latitude="+location.getLatitude());
textView3.setText("Longitude="+ location.getLongitude());
textView4.setText("Distance="+ distanza);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prova.mapapplicationprove">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Per usare il GPS -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.prova.mapapplicationprove.MainActivity" />
</activity>
</application>
</manifest>
I think you should put
distance = location.distanceTo(locationSede); //LINE NUMBER 61
into method
#Override
public void onLocationChanged(Location location) {
}
It'll look like
#Override
public void onLocationChanged(Location location) {
if (location != null){
Location locationSede = new Location("Sede");
locationSede.setLatitude(45.012447);
locationSede.setLongitude(7.621013);
int distance = location.distanceTo(locationSede);
}
}
If you want to calculate distance between 2 points then you can use to Location.distanceBetween( A.Latitude, A.Longitude, B.Latitude, B.Longitude, result);
See below code how to impliment in your code
float[] result = new float[1];
Location.distanceBetween(location.getLatitude(), location.getLongitude(), locationSede.getLatitude(), locationSede.getLongitude(), result);
Log.e("TAG Result",""+result); //Here result is your distance
double km = result * 0.001;
Log.e("TAG Result",""+km); //Here distance in kilometer
Here when you want to distance in kilometer that time total distance with multiply 0.001 as like distancein_km=total_dis*001
I resolve my problem, the error is caused by the provider: I use locationManager.allProvider(); and in this way it works.
Thanks anyway

LocationManager requestLocationUpdates not working

I Have This Creepy problem. i am trying to get the location of my emulator. it working fine when i get the location of my emulator. but when i change my location coordinates nothing happens. gps is working fine.
Here is my code
Main.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Main extends Activity {
TextView tvStatus;
LocationManager lm;
boolean gpsEnabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView) findViewById(R.id.textView1);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("", "GPS is Active");
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tvStatus.setText(l.getLatitude()+" , "+l.getLongitude());
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1,
Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
tvStatus.setText("GPS ENABLED: " + gpsEnabled
+ "\nLatitude: " + arg0.getLatitude()
+ "\nLongitude: " + arg0.getLongitude());
}
});
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabelinglocationprovider"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.enabelinglocationprovider.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Samsung phones have this problem. There is hack to this. You need to kick the locationmanager on the butt to get the latest location from the maps cache.
God.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
currentLocation = God.locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Call getLastKnownLocation after kicking the requestLocationUpdates with 0's.
It happens with emulators, try rebooting the emulator.
Or, close both eclipse and emulator and start both again

getting altitude/latitude/longitude from GPS

I am trying to run the code below to get the user location (altitude/latitude/longitude) but it's not working. During the debugging is appearing the following message:
_No command output when running: 'am start -D -n net.learn2develop.get_location/net.learn2develop.get_location.Getting_CoordinatesActivity -a android.intent.action.MAIN -c android.intent.category.LAUNCHER' on device emulator-5554_
com.android.ddmlib.ShellCommandUnresponsiveException
at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:408)
at com.android.ddmlib.Device.executeShellCommand(Device.java:276)
at com.android.ide.eclipse.adt.internal.launch.ActivityLaunchAction.doLaunchAction(ActivityLaunchAction.java:74)
at com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController.launchApp(AndroidLaunchController.java:1147)
at com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController.clientChanged(AndroidLaunchController.java:1493)
at com.android.ddmlib.AndroidDebugBridge.clientChanged(AndroidDebugBridge.java:870)
at com.android.ddmlib.Device.update(Device.java:398)
at com.android.ddmlib.Client.update(Client.java:835)
at com.android.ddmlib.HandleAppName.handleAPNM(HandleAppName.java:90)
at com.android.ddmlib.HandleAppName.handleChunk(HandleAppName.java:64)
at com.android.ddmlib.MonitorThread.callHandler(MonitorThread.java:414)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:322)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
What could be wrong/missing?
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.get_location"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Getting_CoordinatesActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Java Code:
package net.learn2develop.get_location;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class Getting_CoordinatesActivity extends Activity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
public void onLocationChanged(Location location) {
String Text = "Latitude = " + location.getLatitude() +
"\nLongitude = " + location.getLongitude() +
"\nAltitude = " + location.getAltitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_LONG ).show();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected void onDestroy(){
super.onDestroy();
//getLocationManager().removeUpdates( this );
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, myLocationListener);
}
}
Thanks in advance
Try sending lat and long coordinates through DDMS perspective.

Categories

Resources