Most of the time it is required to get gps data even when application is not running. To make an application receive the gps reading in background, We use Service. Service runs in background even when your application is not on the front and you are using some other application.
Expected Result :
Service will run at background forever and it will update location at specific time interval to the server
here is the implementation of code :
Steps 1 : Create MyLocationManager.java class
Here the class to get current GPS location using Location listener.
Steps 2 : Create GpsService.java
-Its a service which run in background forever for capture location. Its has timer to set its Time interval for repeatedly at some interval.
Steps 3 : Create MainActivity.java
Steps 4 : Create AndroidManifest.xml
Add following permission on AndroidManifest.xml And add service
Expected Result :
Service will run at background forever and it will update location at specific time interval to the server
here is the implementation of code :
Steps 1 : Create MyLocationManager.java class
Here the class to get current GPS location using Location listener.
import android.app.AlertDialog;
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.provider.Settings;
public class MyLocationManager implements LocationListener
{
private Context mContext = null;
LocationManager mLocationManager = null;
public MyLocationManager(Context context)
{
this.mContext = context;
mLocationManager = (LocationManager)this.mContext.getSystemService(Context.LOCATION_SERVICE);
}
public Location getLocation()
{
Location mLocation = null;
if(isGPSEnable() != true
&& isNetWorkProviderEnable() != true)
{
}
else
{
if(isGPSEnable())
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0F, this);
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(mLocation == null
&& isNetWorkProviderEnable() == true)
{
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0F, this);
mLocation = mLocationManager.getLastKnownLocation("network");
}
}
else
{
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0F, this);
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
return mLocation;
}
public boolean isGPSEnable()
{
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean
isNetWorkProviderEnable()
{
return mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
@Override
public void
onLocationChanged(Location location)
{
}
@Override
public void
onProviderDisabled(String provider)
{
}
@Override
public void
onProviderEnabled(String provider)
{
}
@Override
public void
onStatusChanged(String provider, int
status, Bundle extras)
{
}
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting
Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting
Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On
Pressing Setting button
alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
{
@Override
public void
onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On
pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
@Override
public void
onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
}
Steps 2 : Create GpsService.java
-Its a service which run in background forever for capture location. Its has timer to set its Time interval for repeatedly at some interval.
import
java.io.BufferedWriter;
import java.io.File;
import
java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import
java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import
android.content.Context;
import
android.content.Intent;
import
android.net.ConnectivityManager;
import android.net.NetworkInfo;
import
android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import
android.widget.Toast;
public class GpsService extends Service
{
private Timer mTimer;
GPSTracker
gpsTracker;
@Override
public void onCreate()
{
Log.d("onCreate","onCreate
called...");
mTimer = new Timer();
}
@Override
public int
onStartCommand(Intent intent, int flags, int startId)
{
Log.d("onStartCommand","onStartCommand
called...");
mTimer.scheduleAtFixedRate(new MyTimerTask(), 0, 10000);//10 seconds
return START_STICKY;
}
@Override
public IBinder
onBind(Intent intent)
{
return null;
}
@Override
public void onDestroy()
{
mTimer.cancel();
Toast.makeText(this, "Service
Destroyed", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
private class MyTimerTask extends TimerTask {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
}
private final Handler handler = new Handler()
{
@Override
public void
handleMessage(Message msg)
{
Toast.makeText(getApplicationContext(),
"Refreshing...", Toast.LENGTH_SHORT).show();
SimpleDateFormat
dateFormat=new SimpleDateFormat("dd/mm/yyyy hh:MM:ss");
Log.i("BackService", dateFormat.format(new Date()));
if(isOnline(getApplication()))
{
try
{
MyLocationManager
manager = new MyLocationManager(getApplicationContext());
Log.e("", ""+manager.getLocation().getLatitude()+","+manager.getLocation().getLongitude());
WriteLog("Lat & lng
="+manager.getLocation().getLatitude()+","+manager.getLocation().getLongitude());
}
catch (Exception e)
{
WriteLog("Exception
="+e.toString());
}
}
else
{
WriteLog("Internet is
not available in device");
}
}
};
public static void WriteLog(String
LogMessage)
{
SimpleDateFormat
dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String
formatedDate=dateFormat.format(new Date());
LogMessage
= "\n\n"+formatedDate+"\n" +LogMessage;
File
root = Environment.getExternalStorageDirectory();
File
logDir = new File(root + "/TrakingLog");
if(!logDir.exists())
{
logDir.mkdirs();
}
else if(logDir.exists())
{
try
{
SimpleDateFormat
dateFormat1 = new SimpleDateFormat("dd-MM-yyyy");
String dt=dateFormat1.format(new Date());
File
file = new File(logDir,dt+".txt");
if(!file.exists())
{
file.createNewFile();
FileWriter
fw = new FileWriter(file, true);
BufferedWriter
bw = new BufferedWriter(fw);
bw.write("---TRACKING
ON ("+dt+")---\n");
bw.flush();
bw.close();
}
else if(file.exists())
{
FileWriter
fw = new FileWriter(file, true);
BufferedWriter
bw = new BufferedWriter(fw);
bw.append(LogMessage);
bw.flush();
bw.close();
}
}
catch
(FileNotFoundException e)
{
Log.d("File not
fond",
e.getMessage());
}
catch (IOException e)
{
Log.d("File
I/O",
e.getMessage());
}
catch (Exception e)
{
Log.d("Log File
exception", e.getMessage());
}
}
}
public static boolean isOnline(Context
context)
{
ConnectivityManager
cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo
netInfo = cm.getActiveNetworkInfo();
if (netInfo != null &&
netInfo.isConnectedOrConnecting()&&
cm.getActiveNetworkInfo().isAvailable()&&
cm.getActiveNetworkInfo().isConnected())
{
return true;
}
return false;
}
}
import
android.app.Activity;
import
android.content.Intent;
import android.os.Bundle;
import android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
public class MainActivity extends Activity
{
Button
btnStart,btnStop;
MyLocationManager
locationManager;
@Override
protected void onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager=new
MyLocationManager(MainActivity.this);
btnStart=(Button)
findViewById(R.id.btnStart);
btnStop=(Button)
findViewById(R.id.btnStop);
btnStart.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(locationManager.isGPSEnable())
{
startService(new
Intent(getBaseContext(), GpsService.class));
}
else
{
locationManager.showSettingsAlert();
}
}
});
btnStop.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
stopService(new
Intent(getBaseContext(), GpsService.class));
}
});
}
}
Add following permission on AndroidManifest.xml And add service
<uses-permission android:name="android.permission.INTERNET"
/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
<uses-permission android:name="android.permission.WAKE_LOCK"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<service android:name="GpsService"
android:exported="false" />
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)
No comments:
Post a Comment