Android battery level - android

I have a problem with an application that sends coordinates via SMS.
When I added the battery level, the application stopped working after catching the fix.
(Coordinates not on display, but they are via SMS.)
Please help.
ZoltrixGPSActivity
package com.zoltrix.gps;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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 {
// Here I added a level of battery (1)
private TextView contentTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
}
};
// end
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);
// Here I added a level of battery (2)
contentTxt = (TextView) this.findViewById(R.id.battery);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
// end
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("lon", Double.toString(pLong));
i.putExtra("lat", Double.toString(pLat));
i.putExtra("alt", Double.toString(pAlt));
i.putExtra("acc", Float.toString(PAcc));
i.putExtra("spe", Float.toString(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
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 LON = extras.getString("lon");
String LAT = extras.getString("lat");
String ALT = extras.getString("alt");
String ACC = extras.getString("acc");
String SPE = extras.getString("spe");
sendSMS("510104727", "LON" + LON + "#" + "LAT" + LAT + "#"
+ "ALT" + ALT + "#" + "ACC" + ACC + "#" + "SPE" + 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" >
</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>
Loyout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude "
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alt"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textAlt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Provider"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textPro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accuracy (m)" />
<TextView
android:id="#+id/textAcc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/text344"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speed (m/s)" />
<TextView
android:id="#+id/textSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/battery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/btnSendSMS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send" />
<Button
android:id="#+id/buttonExit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
LogCat
http://pastebin.com/whhdHsyw

Try adding the android.permission.BATTERY_STATS permission to your code.
<uses-permission android:name="android.permission.BATTERY_STATS" />

// Put this Code into your MainActivity where you want to show level
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
int level = i.getIntExtra("level", 0);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
pb.setProgress(level);
TextView tv = (TextView) findViewById(R.id.textfield);
tv.setText("Battery Level: " + Integer.toString(level) + "%");
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
// Please Add the given below code into manifest:
<uses-permission android:name="android.permission.BATTERY_STATS" />

Related

Code with no errors crashes when testing on mobile

I am extremely new when it comes to Android Studio but have managed to put together 2 activities which work fine under separate apps, but when joined, it crashed when the MainActivity calls AddressActivity usingIntent and startActivity.
There is another problem which maybe related or may not be. When installing the app, there are NO permissions requested.
Here is my code:
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<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>
<activity
android:name=".AddressActivity"
android:label="login">
</activity>
</application>
MainActivity.class
package crproductionsptyltd.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static crproductionsptyltd.login.R.id.driverid;
import static crproductionsptyltd.login.R.id.login;
public class MainActivity extends Activity {
EditText driverid;
Button btnOk;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// find View-elements
btnOk = (Button) findViewById(login);
// btnOk.setOnClickListener(this)
// create click listener
View.OnClickListener oclBtnOk = new View.OnClickListener() {
#Override
public void onClick(View v) {
// change text of the TextView (tvOut)
btnOk.setText("Logging IN.....");
Intent i = new Intent(MainActivity.this, AddressActivity.class);
i.putExtra("driver_id", driverid.getText().toString());
startActivity(i);
};
};
// assign click listener to the OK button (btnOK)
btnOk.setOnClickListener(oclBtnOk);
// startActivity(new Intent(MainActivity.this, AddressActivity.class));
// Intent i = new Intent(MainActivity.this, NewActivity.class);//
// startActivity(i);
};
}
AddressActivity.class
package crproductionsptyltd.login;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
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;
import android.content.Intent;
public class AddressActivity extends Activity {
/**
* Called when the activity is first created.
*/
String lat = "", lon = "";
TextView tvView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
tvView = (TextView) findViewById(R.id.tvView);
Intent intent = getIntent();
String driverid = intent.getStringExtra("driver_id");
tvView.setText("Your Driver ID is: " + driverid);
Button btnLocation = (Button) findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.txtLoc);
tv.setText("Your Location is:" + lat + "--" + lon);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
});
Button btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
postData(lat, lon);
}
});
Button btnAdd = (Button) findViewById(R.id.btnAddress);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.txtAddress);
tv.setText(GetAddress(lat, lon));
}
});
}
public void postData(String la, String lo) {
//URL url = new URL("https://www.autoflora.net/driver/gps.php?Driver_ID=877&latlong=" + lat + "*" + lon);
int TIMEOUT_VALUE = 15000;
try{
URL myUrl = new URL("https://www.autoflora.net/driver/gps.php?Driver_ID=877&latlong=" + lat + "*" + lon);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(TIMEOUT_VALUE);
connection.connect();
} catch (Exception e) {
}
}
public String GetAddress(String lat, String lon)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
}
activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="crproductionsptyltd.login.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/driverid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Driver ID"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/login"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"
android:textStyle="bold"
android:onClick="checkDriver" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_gps.class
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLoc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/tvView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textSize="20sp">
</TextView>
<Button
android:id="#+id/btnLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get my Location" />
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Location" />
<Button
android:id="#+id/btnAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Try Get Street Address" />
<TextView
android:id="#+id/txtAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Based on your code, the app will crash here: i.putExtra("driver_id", driverid.getText().toString()), resulting in a NullPointerException. It crashes because you don't have an initialisation for EditText driverid; in onCreate and thus, it will throw an exception when used uninitialised.
To fix the problem you have to update the field in onCreate:
driverid = (EditText) findViewById(driverid);
I think, to use android.support.design.widget.TextInputLayout
you should use these dependencies
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
& also please correct
btnOk = (Button) findViewById(R.id.login); //wrongly added
driverid = (EditText) findViewById(R.id.driverid); // not added

Trouble in getting Location in Android SDK

I am new to Android, trying to implement Location Based Service but, I am getting errors. I am getting confused now.
Here are my files:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.om.locationdemo.MainActivity">
<Button
android:text="Get Location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/button" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="37dp" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:id="#+id/button2" />
</RelativeLayout>
**AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.om.locationdemo">
<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>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.om.locationdemo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContext;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1, b2;
TextView tv;
LocationManager lmngr;
LocationListener llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
tv = (TextView) findViewById(R.id.textView);
lmngr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
llm = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
tv.setText("Latitude = " + location.getLatitude() + " Longitude's = " + location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(MainActivity.this, "Please Enable Location Service", Toast.LENGTH_LONG).show();
}
};
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lmngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, llm);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lmngr.requestLocationUpdates
(LocationManager.NETWORK_PROVIDER,0, 0, llm);
}
});
}
}

longitude and latitude acquiring (Android) + reverse geocoding

So i put together a few snippets that i found here and there; aiming to make a more complex app, however, at one point i was able to obtain the the longitude and latitude number, but once I've tried supply those number to the reverse GeoCoding mechanism, i have not been able to get the Long and Lat numbers and the app crashes after i click the button (which does the reverse geocoding)
package com.example.com.example;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button myLocation;
TextView myAddress;
TextView textLat;
TextView textLong;
double latHolder = 0.0;
double longHolder = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocation= (Button) findViewById(R.id.location);
myAddress = (TextView)findViewById(R.id.address);
textLat = (TextView)findViewById(R.id.textLat); ///COORDINATION VARIABLES1
textLong = (TextView)findViewById(R.id.textLong);///2
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //gets it from the Operating system
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); //LOCATION UPDATED LINKED
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
textLat.setText("GPS ONLINE (PLEASE WAIT)");
textLong.setText("GPS ONLINE (PLEASE WAIT)");
}
else
{
textLat.setText("GPS OFFLINE");
textLong.setText("GPS OFFLINE");
}
myLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getMyLocationAddress();
}
});
}
///////////COORDIATION ACQUIRING DOWN HERE
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
double pLat = location.getLatitude();
double pLong = location.getLongitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
latHolder = pLat;
longHolder = pLong;
}
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
public void getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latHolder,longHolder, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText("I am at: " +strAddress.toString());
}
else
myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
Here is my Manafist with all permissions which should be enough
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<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=".MainActivity"
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>
and last but not lease my xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LATITUDE" />
<Button
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/address"
android:layout_below="#+id/address"
android:layout_marginTop="79dp"
android:text="get_location" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="135dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="44dp"
android:text="LONGITUD" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title" />
</RelativeLayout>
DO PLEASE NOTE! i have added two global variables called LongHolder and LatHolder to pass the values of the GPS straight to the reverse geocoding. I believe they failed their purpose but if you need to test random selected Coordinates yourself, remember to remove them. THANK YOU

GPS implementation: provider enabled

I try to implement a gps application, (I take the code from a guide) but doesn't work!
I think the problem is the provider enabled, so the app can't calculate the latitude and longitude.
Please help me, thank you.
package it.wstech.gps;
import java.util.Date;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;
public class GPSMainActivity extends Activity {
private String providerId= LocationManager.GPS_PROVIDER;
private LocationListener myLocationListener= new LocationListener(){
//methods of Location Listener interface
#Override
public void onStatusChanged (String provider, int status, Bundle extras){
if (status==LocationProvider.AVAILABLE){
setTextViewValue(R.id.available,"TRUE");
}
else {
setTextViewValue(R.id.available,"FALSE");
}
}
#Override
public void onProviderEnabled (String provider){
setTextViewValue(R.id.enabled,"TRUE");
}
#Override
public void onProviderDisabled (String provider){
setTextViewValue(R.id.enabled,"FALSE");
}
#Override
public void onLocationChanged (Location location){
updateLocationData(location);
}
};
//activity methods
#Override
public void onCreate (Bundle savedIstanceState){
super.onCreate(savedIstanceState);
setContentView(R.layout.activity_gpsmain);
}
#Override
protected void onResume(){
super.onResume();
setTextViewValue(R.id.provider,providerId);
LocationManager locationManager = (LocationManager) getSystemService (LOCATION_SERVICE);
LocationProvider provider= locationManager.getProvider(providerId);
if (provider== null) {
setTextViewValue (R.id.available,"FALSE");
} else {
setTextViewValue (R.id.available,"TRUE");
boolean gpsEnabled=locationManager.isProviderEnabled(providerId);
if (gpsEnabled){
setTextViewValue (R.id.enabled,"TRUE");
}
else {
setTextViewValue (R.id.enabled,"FALSE");
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location !=null){
updateLocationData(location);
}
locationManager.requestLocationUpdates(providerId, 5, 1,myLocationListener);
}
}
#Override
protected void onPause(){
super.onPause();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.removeUpdates(myLocationListener);
}
private void setTextViewValue (int textViewId, String value){
TextView testView=(TextView) findViewById(textViewId);
if (testView!=null){
testView.setText(value);
}
}
private void updateLocationData(Location location){
Date timestamp= new Date (location.getTime());
setTextViewValue (R.id.timestamp, timestamp.toString());
double latitude=location.getLatitude();
setTextViewValue (R.id.latitude, String.valueOf(latitude));
double longitude = location.getLongitude();
setTextViewValue (R.id.longitude, String.valueOf(longitude));
if (location.hasAltitude()){
double altitude = location.getAltitude();
setTextViewValue (R.id.altitude, String.valueOf(altitude));
}
if (location.hasSpeed()){
float speed=location.getSpeed();
setTextViewValue(R.id.speed, String.valueOf(speed));
}
}
}
My activity_gpsmain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:padding="5px">
<TextView
android:text="Provider"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/provider"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Disponibile"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/available"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Abilitato"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/enabled"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Timestamp"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/timestamp"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Latitudine"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/latitude"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Longitudine"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/longitude"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Altitudine"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/altitude"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Velocità"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/speed"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>
my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.wstech.gps"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".GPSMainActivity"
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>
Result:
Provider gps
Disponibile TRUE
Abilitato false
Timestamp
Latitudine
Longitudine false
Altitudine false
Velocità false
Try this code and get latitude and longitude
Create a class GPSTracker.java
package com.example.gpstracker;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener
{
private final Context _context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=5; //5 meters
private static final long MIN_TIME_BW_UPDATES=1000*60*1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context contet)
{
this._context=contet;
getLocation();
}
public Location getLocation()
{
try
{
locationManager =(LocationManager)_context.getSystemService(LOCATION_SERVICE);
//getting GPS Status
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
}
else
{
this.canGetLocation=true;
//first get location from network provider
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("Network","Network");
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
// if GPS Enabled get lat/log
if(isGPSEnabled)
{
if(location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("GPS","GPS Enabled");
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location !=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location !=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation()
{
return this.canGetLocation;
}
public void showSettingAlert()
{
AlertDialog.Builder alert=new AlertDialog.Builder(_context);
alert.setTitle("GPS is Setting");
alert.setMessage("GPS is not enabled. Do you want to go to settings..?");
alert.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
_context.startActivity(i);
}
});
alert.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Create your activity class file MainActivity.java
package com.example.gpstracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button btnClick;
GPSTracker tracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick=(Button)findViewById(R.id.btnClick);
btnClick.setOnClickListener(this);
}
#Override
public void onClick(View v) {
tracker=new GPSTracker(getApplicationContext());
if(tracker.canGetLocation())
{
double latitude=tracker.getLatitude();
double longitude=tracker.getLongitude();
Toast.makeText(MainActivity.this,"your Location is \n Latitude : " + latitude +
"\n Longitude : "+longitude,Toast.LENGTH_LONG).show();
}
else
{
tracker.showSettingAlert();
}
}
}
Add below lines in manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

application doesn't seem to do anything

(ANDROID GPS)
i made this application to send gps coordinates via sms but it doesn't seem to do any thing can anybody tell me what am i missing??
this is what logcat have to say on pressing the button
logcat image1
logcat image2
MainActivity.java
package com.adzz.gps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager manager= (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener =new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
final String phoneNumber="9453603045";
double lat1=location.getLatitude();
Double d1= new Double(lat1);
double longi1=location.getLongitude();
Double d2=new Double(longi1);
m="latitude = "+ d1.toString() + "and latitude = "+ d2.toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, m, null, null);
TextView lat= (TextView) findViewById(R.id.lat);
TextView longi=(TextView) findViewById(R.id.longi);
lat.setText("latitude = "+lat1);
longi.setText("longitude ="+longi1);
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 25,
listener);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast toast=Toast.makeText(Main.this, m, 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/longi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:id="#+id/button1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adzz.gps001"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses- permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.adzz.gps001.MainActivity"
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>
How about adding the permission for SMS in your AndroidManifest.xml?
<uses-permission android:name="android.permission.SEND_SMS" />

Categories

Resources