GPS implementation: provider enabled - android

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"/>

Related

android: not able to find the location by using FusedLocationApi even after enabling GPS

I'm trying to find the location of the mobile using GPS and FusedLocationApi location. Even after enabling the GPS i'm not getting the location details. Below is the steps i followed. Kindly Help me Out.
Step 1:-
Added the line in my gradle
compile 'com.google.android.gms:play-services-location:8.1.0'
Step 2:-
MainActivity File
package com.developer.kamalasekar.locationfinder;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
}
Step3:-
ActivityMain
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="#+id/latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Latitude:"
android:textSize="18sp" />
<TextView
android:id="#+id/latitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/latitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/latitude"
android:textSize="16sp" />
<TextView
android:id="#+id/longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Longitude:"
android:layout_marginTop="24dp"
android:textSize="18sp" />
<TextView
android:id="#+id/longitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/longitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/longitude"
android:textSize="16sp"/>
</RelativeLayout>
Step 4:-
Added the lines in my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.developer.kamalasekar.locationfinder">
<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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
There is a possibility that in onConnected if you call LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); may return null when location not found. But if you execute the same line again after few seconds (1/2 secs and gps enabled ) then you definitely get location for sure.
#Override
public void onConnected(Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
//your stuff
} else {
handler.sendEmptyMessageDelayed(1, 2000);
}
}
int count;
android.os.Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (count < 2) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null){
handler.sendEmptyMessageDelayed(1, 2000);
}else{
//your stuff
}
count++;
} else{
Log.i("MyTag","location not found");
}
}
};
or visit Android: Location Updates with the FusedLocationApi
or you can follow #user2450263 post by setting LocationListener.

LocationManager doesn't work, without any error

If I click "Find My Location" button, then my location information should have shown on the TextView, but doesn't work.
It's simple code but I have no idea where did this go wrong. Seems that there's no mistake within the code.. could be the problem of my phone?
MainActivity.java
package org.androidtown.mylocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
public void onButton1Clicked(View v){
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
long minTime = 10000;
float minDistance = 0;
MyLocationListener listener = new MyLocationListener();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
minTime, minDistance, listener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
minTime, minDistance, listener);
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null){
Double latitude = lastLocation.getLatitude();
Double longitude = lastLocation.getLongitude();
textView.setText("My Latest Location: " + latitude + ", " + longitude);
textView.invalidate();
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
textView.setText("My Location: " + latitude + ", " + longitude);
textView.invalidate();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.androidtown.mylocation" >
<!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- NETWORK -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/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>
activity_main.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find My Location"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="onButton1Clicked" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Location"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
</RelativeLayout>

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

Get total distance travelled using GPS doesn't update my location

Hi I'm currently learning about the GPS for development in Android. Now I've read about the basics through vogellas blog here. Now I already get the latitude and longitude and displayed it on my device but I don't know why it doesn't update my location even though I already set a runnable thread to fetch location every 3 seconds. Same reason why I can't check if I got the correct formula to get the total distance I've travelled.
This is my first time working with this so maybe someone can give me a tip or idea on how to.
I created a repository in github maybe someone can help me with this. See file here :)
EDIT:
Okay the main problem is that the onChangeLocation() seems doesn't work on my end. What I tried is to create a runnable to display the location every 3 seconds but it doesn't return the result I expected.
Did I missed out on something here?
Here's my code so far for easier viewing:
Main.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/*created by Kahel 08/16/2013
* to read more about the location manager go here: http://www.vogella.com/articles/AndroidLocationAPI/article.html
*
* */
public class Main extends Activity implements LocationListener {
private TextView latitude, longitude, distance;
private Button getLocation;
private LocationManager locationManager;
private String provider;
double distance_travelled;
double latitude_prev;
double longitude_prev;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latitude = (TextView)findViewById(R.id.txt_latitude);
longitude = (TextView)findViewById(R.id.txt_longitude);
distance = (TextView) findViewById(R.id.txt_distance);
getLocation = (Button)findViewById(R.id.btn_getLocation);
checkGps();
getCurrentLocation();
getLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locatorRunner();
}
});
}
private void locatorRunner(){
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(3000);
runOnUiThread(new Runnable() {
#Override
public void run() {
/*needs UI Thread*/
getCurrentLocation();
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void getCurrentLocation(){
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Toast.makeText(Main.this,String.valueOf(location),Toast.LENGTH_SHORT).show();
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, (LocationListener) location);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latitude.setText("Location not available");
longitude.setText("Location not available");
distance.setText("0");
}
}
private void checkGps(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
Toast.makeText(Main.this,String.valueOf(enabled),Toast.LENGTH_SHORT).show();
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
showGpsSettingDialog();
}
}
private void showGpsSettingDialog(){
/*Create a dialog to tell user to enable his GPS settings to pinpoint his or her location*/
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Main.this);
alertDialog.setTitle("Settings para sa lokasyon"); /*should be on a string values*/
alertDialog
.setMessage("Kasalukuyang hindi aktibo ang iyong GPS para makuha ang iyong lokasyon. Nais mo bang i-set ito ngayon?")
.setCancelable(false)
.setPositiveButton("Oo", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Hindi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog gpsSettingsDialog = alertDialog.create();
gpsSettingsDialog.show();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#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;
}
#Override
public void onLocationChanged(Location location) {
getLocation(location);
}
private void getLocation(Location location){
int R = 6371;
double lat = location.getLatitude();
double lon = location.getLongitude();
latitude_prev = lat;
longitude_prev = lon;
Double dlat = latitude_prev - lat;
Double dlon = longitude_prev - lon;
double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(latitude_prev) *
Math.cos(lat) * Math.sin(dlon / 2) * Math.sin(dlon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
distance_travelled = R * c;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lon));
distance.setText(String.valueOf(distance_travelled));
}
/*private double toRad(double d) {
return d * Math.PI / 180;
}*/
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(this, "Enabled new provider " + provider,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Latitude: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="#+id/txt_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Longitute: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="#+id/txt_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Distance Travelled:"
android:id="#+id/textView"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="unknown"
android:id="#+id/txt_distance"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="#+id/btn_getLocation"
android:layout_gravity="center"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geolocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION " />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.geolocation.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>
Note:
I added the button Start Tracking because I'm not sure if the onLocationChanged is working or not. hahaha!
Basic approach for distance:
public class test extends Activity implements LocationListener{
private LocationManager lm;
private Location last;
private long distance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,1,this);
}
#Override
protected void onPause() {
super.onPause();
lm.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if(last != null){
distance += location.distanceTo(last);
}
last = new Location(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
You have to implement LocationListener to get current GPS location something like this :
Set user permission firlst
Now get GPS location like this :
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
//Get your location here
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
You can call getCurrentLocation() every 3 second but this will not trigger getLocation(location);.
getLocation(location); will be called only when Location gets updated
#Override
public void onLocationChanged(Location location) {
getLocation(location);
}

Android battery level

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" />

Categories

Resources