I want to Current location and sent that location on my ASP.Net Web service.
I write following code.
Background Service is start by using this code but i don`t get Location.
OnLocationChange() Method is not called.
Please Help me.
Following Code:
Set Alarm Code:
#TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean AlarmSet(Context context, String function, AlarmManager alarmMan) {
AlarmManager alarmManager = alarmMan;
PendingIntent pending_intent;
DatabaseHandler DB;
try {
DB = new DatabaseHandler(context);
String state = function;
final Intent myIntent = new Intent(context, AlarmReceiver.class);
final Calendar calendar = Calendar.getInstance();
if (state.contains("setall")) {
String result = DB.ConvStrSelctTripTimeDetails();
String[] row = result.split("####");
for (int i = 0; i < row.length; i++) {
String[] data = row[i].split("#");
int rowid = Integer.parseInt(data[0]);
int shiftid = Integer.parseInt(data[1]);
int dayid = Integer.parseInt(data[2]);
if (dayid != 7) {
dayid = dayid + 1;
} else {
dayid = 1;
}
String[] strtIN = data[3].split(":");
String[] endIN = data[4].split(":");
String[] strtOUT = data[5].split(":");
String[] endOUT = data[6].split(":");
String alarmStartIN = "1";
//IN_Start
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strtIN[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(strtIN[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "s");
alarmStartIN = String.valueOf(rowid) + "1";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//IN_End
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endIN[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(endIN[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "e");
alarmStartIN = String.valueOf(rowid) + "2";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//OUT_Start
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strtOUT[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(strtOUT[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "s");
alarmStartIN = String.valueOf(rowid) + "3";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//OUT_End
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endOUT[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(endOUT[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "e");
alarmStartIN = String.valueOf(rowid) + "4";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
}
return true;
} catch (Exception ex) {
common.writelog("common", "AlarmSet() Value:"+ function +": Error:361:" + ex.getMessage());
Log.e("common", "onCreate() Value:"+ function +": Error:361:" + ex.getMessage());
return false;
}
}
AlarmReceiver File Code:
public class AlarmReceiver extends BroadcastReceiver {
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 180000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 180000;
#Override
public void onReceive(Context context, Intent intent) {
String ShiftID = intent.getExtras().getString("ShiftID");
Log.e("AlarmReceiver", "onReceive() ShiftID : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() ShiftID : " + ShiftID);
if(context==null)
{
Log.e("AlarmReceiver","Context:null");
}
else
{
Log.e("AlarmReceiver","Context:Not null");
}
String ops = intent.getExtras().getString("ops");
Log.e("AlarmReceiver", "onReceive() ops : " + ops);
common.writelog("AlarmReceiver", "onReceive() ops : " + ops);
if (ops.equals("s")) {
try {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean statusOfGPS = manager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*
* if (!statusOfGPS) { showGPSDisabledAlertToUser(); }
*/
// startAt10();
// start();
common.Running = true;
buildGoogleApiClient(context);
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception ex) {
Log.e("AlarmReceiver", "onReceive() Error: 48 : " + ex.getMessage());
common.writelog("AlarmReceiver", "onReceive() ShiftID : " + ex.getMessage());
}
Log.e("AlarmReceiver", "onReceive() Start Service : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() Start Service : " + ShiftID);
Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.putExtra("ShiftID", ShiftID);
serviceIntent.putExtra("ops", ops);
assert context != null;
context.startService(serviceIntent);
//context.startService(new Intent(context, MyService.class));
} else if (ops.equals("e")) {
Log.e("AlarmReceiver", "onReceive() End Service : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() End Service : " + ShiftID);
Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.putExtra("ShiftID", ShiftID);
serviceIntent.putExtra("ops", ops);
assert context != null;
context.stopService(serviceIntent);
}
}
protected synchronized void buildGoogleApiClient(Context contex) {
mGoogleApiClient = new GoogleApiClient.Builder(contex)
.addApi(LocationServices.API).build();
createLocationRequest();
}
private void createLocationRequest() {
try {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest
.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}catch (Exception ex)
{
common.writelog("AlarmReceiver", "createLocationRequest()86: " + ex.getMessage());
}
}
}
MyService Code:
package com.expedite.apps.vehiclelocation;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.format.Time;
import android.util.Log;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 2f;
private static String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION_VISITED = "http://tempuri.org/setVechicleLocation";
private static String METHOD_SEND_LOCATION_DATA = "setVechicleLocation";
private static String URL = "http://vts.vayuna.com/Service.asmx";
public String buskey = "";
boolean isget = false;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
try {
Log.e(TAG, "LocationListener " + provider);
common.writelog(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
} catch (Exception ex) {
Log.d(TAG, "LocationListener() Error:48 " + ex.getMessage());
common.writelog(TAG, "LocationListener() Error:48 " + ex.getMessage());
}
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
try {
mLastLocation.set(location);
Time time = new Time();
time.setToNow();
if (common.lat != location.getLatitude() || common.lon != location.getLongitude() || common.minut != time.minute) {
common.lat = location.getLatitude();
common.lon = location.getLongitude();
common.accu = location.getAccuracy();
common.minut = time.minute;
common.time = time.hour + ":" + time.minute + ":" + time.second;
new MyTask().execute();
common.writelog(TAG, "onLocationChanged: " + location.getAccuracy());
} else {
}
// Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
common.writelog(TAG, "onStatusChanged: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
common.writelog(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
common.writelog(TAG, "onProviderDisabled: " + provider);
}
}
/* LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};*/
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER)
};
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Log.e(TAG, "onStartCommand");
common.writelog(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
} catch (Exception ex) {
Log.d(TAG, "onStartCommand() Error:120 " + ex.getMessage());
common.writelog(TAG, "onStartCommand() Error:120 " + ex.getMessage());
return 0;
}
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
common.writelog(TAG, "onCreate");
DatabaseHandler DB = new DatabaseHandler(getApplicationContext());
String Res = DB.ConvStrBusMaster();
if (!Res.equals("")) {
try {
String[] respons = Res.split("####");
buskey = respons[3].toString();
Log.e("MyService", "onCreate() buskey"+buskey);
common.writelog("MyService", "onCreate() buskey"+buskey);
} catch (Exception ex) {
common.writelog("MyService::onCreate()", "Error: 121 MSG:" + ex.getMessage());
Log.e("MyService", "onCreate() Error: 121 MSG:" + ex.getMessage());
}
}
/* Log.e(TAG, "onCreate");
common.writelog(TAG, "onCreate");
if (isget == false) {
buskey =common.busid;
isget = true;
}*/
initializeLocationManager();
/* try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
common.writelog(TAG, "fail to request location update, ignore::: "+ ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
common.writelog(TAG, "network provider does not exist, " + ex.getMessage());
}*/
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
common.writelog(TAG, "fail to request location update, ignore::: "+ ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
common.writelog(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
try {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}catch ( Exception ex)
{
Log.d(TAG, "initializeLocationManager() Error:202 " + ex.getMessage());
common.writelog(TAG, "initializeLocationManager() Error:202 " + ex.getMessage());
}
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
SendDataToServer();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
public void SendDataToServer() {
// $,GJ05AV4839,4503791073,140416111538,21.172227,72.849145,0,0,0,0,#
SoapObject request = new SoapObject(NAMESPACE,
METHOD_SEND_LOCATION_DATA);
Time time = new Time();
String LocationDetails = "";
try {
if (common.lat != 0.0 && common.lon != 0.0) {
time.setToNow();
String m_androidId = "Service "
+ Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy:HH:mm:ss");
String currentTimeStamp = dateFormat.format(new Date());
/*LocationDetails = "$,XPD55," + time.hour + ":" + time.minute
+ ":" + time.second + "," + common.time + " Accuracy:"
+ common.accu + "," + common.lat + "," + common.lon
+ ",0,0,0," + m_androidId + ",#";*/
LocationDetails="$," + buskey + "," + buskey + "," + currentTimeStamp + "," + common.lat + ","
+ common.lon + ",0,0,Accuracy:" + common.accu + ",0,#";
common.writelog("Service", "SendLocation() 311:"+ common.lat+","+ common.lon+","+common.accu+", Details::"+LocationDetails+" , Url:"+URL);
request.addProperty("vehicleinfo", LocationDetails);
request.addProperty("device", buskey);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,
100000);
androidHttpTransport.call(SOAP_ACTION_VISITED, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
common.writelog("MyService","SendDataToServer()"+LocationDetails);
}
} catch (Exception ex) {
common.writelog("Service", "Exception 288:" + ex.getMessage()
+ ":::/n" + ex.getStackTrace());
}
}
}
Related
I want to track the user location. So I have made a code so that on every 10 mins of interval its location should be hit on server. If it is not moving also the location should hit at 10 min of interval. I set Location interval minutes for 10 min public static final long LOCATION_INTERVAL_MINUTES = 10 * 60 * 1000;
It should update the location with 10 min, but it hits randomly. I also increase the gps frequency distance from 10 to gpsFreqInDistance = 100 .Random hits are stopped but it will not updated on 10 mins of interval.
So what to do to get location at 10 min of interval.
Below is my manifiest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
As for Android above 10version u cant use background location and foreground location simultaneously. So i comment the ACCESS_BACKGROUND_LOCATION" in my project.
public class LocationMonitoringService implements LocationListener, GpsStatus.Listener {
private static final String TAG = LocationMonitoringService.class.getSimpleName();
private Context mContext;
private LocationRepository mLocationRepository;
private ShareLocationAdapterClass mAdapter;
private SyncOfflineRepository syncOfflineRepository;
private long updatedTime = 0;
private List<UserLocationPojo> mUserLocationPojoList;
private SyncOfflineAttendanceRepository syncOfflineAttendanceRepository;
public LocationMonitoringService(final Context context) {
mContext = context;
mLocationRepository = new LocationRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineRepository = new SyncOfflineRepository(AUtils.mainApplicationConstant.getApplicationContext());
syncOfflineAttendanceRepository = new SyncOfflineAttendanceRepository(AUtils.mainApplicationConstant.getApplicationContext());
mUserLocationPojoList = new ArrayList<>();
mAdapter = new ShareLocationAdapterClass();
mAdapter.setShareLocationListener(new ShareLocationAdapterClass.ShareLocationListener() {
#Override
public void onSuccessCallBack(boolean isAttendanceOff) {
if (isAttendanceOff && !syncOfflineAttendanceRepository.checkIsAttendanceIn()) {
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
}
}
#Override
public void onFailureCallBack() {
}
});
}
public void onStartTacking() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//Exception thrown when GPS or Network provider were not available on the user's device.
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(false);
criteria.setBearingRequired(false);
//API level 9 and up
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
int gpsFreqInDistance = 100;
assert locationManager != null;
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
} catch (IllegalArgumentException | SecurityException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
Log.d(TAG, "onStartTacking: " + e.getLocalizedMessage());
e.printStackTrace();
} catch (RuntimeException e) {
Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
Log.d(TAG, "onStartTacking: " + e.getMessage());
e.printStackTrace();
}
}
public void onStopTracking() {
mAdapter.shareLocation();
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
/*
* LOCATION CALLBACKS
*/
//to get the location change
#Override
public void onLocationChanged(Location location) {
Log.d("okh ", "onLocationChanged: "+System.currentTimeMillis());
if (location != null) {
Log.d(TAG, String.valueOf(location.getAccuracy()));
if (!AUtils.isNullString(String.valueOf(location.getLatitude())) && !AUtils.isNullString(String.valueOf(location.getLongitude()))) {
Prefs.putString(AUtils.LAT, String.valueOf(location.getLatitude()));
Prefs.putString(AUtils.LONG, String.valueOf(location.getLongitude()));
if (Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY, false)) {
if (updatedTime == 0) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
if ((updatedTime + AUtils.LOCATION_INTERVAL_MINUTES) <= System.currentTimeMillis()) {
updatedTime = System.currentTimeMillis();
Log.d(TAG, "updated Time ==== " + updatedTime);
}
sendLocation();
}
}
} else {
Log.d(TAG, "onLocationChanged: no location found !!");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged" + provider + "Status" + status);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, " onProviderEnabled" + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, " onProviderDisabled" + provider);
}
#Override
public void onGpsStatusChanged(int event) {
}
private void sendLocation() {
// mAdapter.shareLocation(getTempList());
Log.d("okh", "sendLocation: Current Time In Millies "+ System.currentTimeMillis());
try {
Calendar CurrentTime = AUtils.getCurrentTime();
Calendar DutyOffTime = AUtils.getDutyEndTime();
if (CurrentTime.before(DutyOffTime)) {
Log.i(TAG, "Before");
UserLocationPojo userLocationPojo = new UserLocationPojo();
userLocationPojo.setUserId(Prefs.getString(AUtils.PREFS.USER_ID, ""));
userLocationPojo.setLat(Prefs.getString(AUtils.LAT, ""));
userLocationPojo.setLong(Prefs.getString(AUtils.LONG, ""));
double startLat = Double.parseDouble(Prefs.getString(AUtils.LAT, "0"));
double startLng = Double.parseDouble(Prefs.getString(AUtils.LONG, "0"));
userLocationPojo.setDistance(String.valueOf(AUtils.calculateDistance(
AUtils.mainApplicationConstant.getApplicationContext(), startLat, startLng)));
// userLocationPojo.setDatetime(AUtils.getServerDateTime()); //TODO
userLocationPojo.setDatetime(AUtils.getServerDateTimeLocal());
userLocationPojo.setOfflineId("0");
if (AUtils.isInternetAvailable() && AUtils.isConnectedFast(mContext))
userLocationPojo.setIsOffline(true);
else
userLocationPojo.setIsOffline(false);
String UserTypeId = Prefs.getString(AUtils.PREFS.USER_TYPE_ID, AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI);
if (AUtils.isInternetAvailable()) {
TableDataCountPojo.LocationCollectionCount count = syncOfflineRepository.getLocationCollectionCount(AUtils.getLocalDate());
if ((UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_GHANTA_GADI) || UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_WASTE_MANAGER))
&& (count.getLocationCount() > 0 || count.getCollectionCount() > 0)) {
syncOfflineRepository.insetUserLocation(userLocationPojo);
} else {
mUserLocationPojoList.add(userLocationPojo);
mAdapter.shareLocation(mUserLocationPojoList);
mUserLocationPojoList.clear();
}
} else {
if (UserTypeId.equals(AUtils.USER_TYPE.USER_TYPE_EMP_SCANNIFY)) {
Type type = new TypeToken<UserLocationPojo>() {
}.getType();
mLocationRepository.insertUserLocationEntity(new Gson().toJson(userLocationPojo, type));
} else {
syncOfflineRepository.insetUserLocation(userLocationPojo);
}
mUserLocationPojoList.clear();
}
}
else {
Log.i(TAG, "After");
syncOfflineAttendanceRepository.performCollectionInsert(mContext,
syncOfflineAttendanceRepository.checkAttendance(), AUtils.getCurrentDateDutyOffTime());
AUtils.setIsOnduty(false);
((MyApplication) AUtils.mainApplicationConstant).stopLocationTracking();
Activity activity = ((Activity) AUtils.currentContextConstant);
if (activity instanceof DashboardActivity) {
((Activity) AUtils.currentContextConstant).recreate();
AUtils.DutyOffFromService = true;
}
if (!AUtils.isNull(AUtils.currentContextConstant)) {
((Activity) AUtils.currentContextConstant).recreate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
Below is the foreground service which i have used
public class ForgroundService extends Service {
private LocationMonitoringService monitoringService;
private Handler locationHandler;
private Runnable locationThread;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
Log.d("okh", "onCreate: " +System.currentTimeMillis());
monitoringService = new LocationMonitoringService(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
Log.d("okh", "onCreate: " +System.currentTimeMillis());
Log.d("okh", "onStartCommand: ");
final int currentId = startId;
locationThread = new Runnable() {
public void run() {
monitoringService.onStartTacking();
}
};
locationHandler = new Handler(Looper.getMainLooper());
locationHandler.post(locationThread);
startLocationForeground();
return Service.START_STICKY;
// return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
//Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
locationHandler.removeCallbacks(locationThread);
monitoringService.onStopTracking();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
{
stopForeground(STOP_FOREGROUND_REMOVE);
}
if(Prefs.getBoolean(AUtils.PREFS.IS_ON_DUTY,false))
{
Intent broadcastIntent = new Intent(this, RestarterBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
}
}
private void startLocationForeground() {
if (Build.VERSION.SDK_INT >= 26) {
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? this.createNotificationChannel("my_service", "My Background Service")
: "";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder((Context) this,
channelId);
Notification notification = notificationBuilder
.setOngoing(true)
.setContentText("Please don't kill the app from background. Thank you!!")
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setPriority(-2)
.setCategory("service")
.build();
startForeground(101, notification);
}
}
#RequiresApi(26)
private String createNotificationChannel(String channelId, String channelName) {
NotificationChannel chan = new NotificationChannel(channelId, (CharSequence)channelName,
NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(chan);
return channelId;
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int color = 0x008000;
notificationBuilder.setColor(color);
return R.drawable.ic_noti_icon;
}
return R.drawable.ic_noti_icon;
}
}
Why you are passing null in the last parameter? Did you try without passing that?
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, AUtils.LOCATION_INTERVAL,
gpsFreqInDistance, this, null);
First of all Google Location Services are far better than Traditional LocationManager to achieve this requirement.
https://developer.android.com/training/location/request-updates
I am having Service using which we are getting the GPS Location by using callback method onLocation. And Android Service gets called every 3 seconds. Now I want to run the Service even if the App is cleared or killed from background.
In onStartCommand we are returning START_STICKY but the service onStartCommand is not getting called after clearing / killing of app.
public class GPSBackgroundService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final String POLL_FREQUENCY = "frequency";
public static final String INITIATED_BY = "initiatedBy";
public static final String INITIATED_SCREEN = "initiated_screen";
ServiceComponent serviceComponent;
//public LocationManager locationManager;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
static Location previousPosition = null;
double preLatitude, preLongitude;
boolean haveLocationPermissionAccess = false, trackStoredLocally = false;
String presentLat = "", presentLon = "";
float totalDistTravelled = 0f;
String dist_travelled = "0", previousDist = "", currentDate = "";
int pollFrequency = 10000;
String speed_calculated = "0.0";
PreferencesHelper mPreferenceHelper;
long preLongTime = 0L;
//handler to update bunch of points in interval seq.
Handler bulkLatLngThroughputManager;
Runnable bulkLatLngThroughputEmployee;
SimpleDateFormat mdformat;
int notificationId = 5173;
NotificationManager notificationManager = null;
/*NotificationManagerCompat notificationManager = null;*/
Notification notification = null;
NotificationCompat.Builder notificationBuilder = null;
String dist = "0.0", text = "";
int count = 0, countForTrackPoints = 0;
static Location currentLocation;
boolean allowForAnotherTrackCall= true;// =true for allowance and =false for dis allowance
int success = 0,fail = 0,init = 0,dbs = 0,dbf = 0, rls=0;
Intent requirementsOfListFragment,requirementsOfMapFragment;
String initiatedBy = "";
static String initiatedScreen = "";
String channelId = "",channelName = "";
Double dist_temp = 0d;
public static boolean allowNetworkCall = true;
#Override
public void onCreate() {
super.onCreate();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onCreate called=" + totalDistTravelled, "abc.txt");
ConfigPersistentComponent configPersistentComponent = DaggerConfigPersistentComponent.builder()
.applicationComponent(SuprabhatApplication.get(getApplicationContext()).getComponent())
.build();
serviceComponent = configPersistentComponent.serviceComponent(new ServiceModule(this));
serviceComponent.inject(this);
mPresenter.attachView(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStartCOMMAND called=" + totalDistTravelled, "abc.txt");
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
notificationBuilder = new NotificationCompat.Builder(this);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MAX)
.setContentText("Live tracking in progress...!")
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setChannelId(channelId)
.build();
notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(notificationId, notification);
}
notificationManager.notify(notificationId, notification);
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStartCOMMAND Leaving=" + totalDistTravelled, "abc.txt");
return START_STICKY;
}
#RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager) {
channelId = "my_service_channelid";
channelName = "My Foreground Service";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
// omitted the LED color
channel.setImportance(NotificationManager.IMPORTANCE_LOW);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
#Override
public void onStart(Intent intent, int startId) {
Log.i("onStart","onStart called");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart called=" + totalDistTravelled, "abc.txt");
pollFrequency = intent.getIntExtra(POLL_FREQUENCY, pollFrequency);
initiatedBy = intent.getStringExtra(INITIATED_BY);
initiatedScreen = intent.getStringExtra(INITIATED_SCREEN);
countForTrackPoints = mPresenter.getTrackLastCount();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart FieldStaffTrans Count="+String.valueOf(countForTrackPoints), "abc.txt");
// Create the Foreground Service
currentDate = CommonUtils.getCurrentDate();
bulkLatLngThroughputManager = new Handler();
bulkLatLngThroughputEmployee = new Runnable() {
#Override
public void run() {
sendTrackedPointsToRemoteLoc(initiatedScreen);
allowForAnotherTrackCall = false;
bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee, pollFrequency);
}
};
mdformat = new SimpleDateFormat("HH:mm:ss");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// stopSelf();
return;
}
haveLocationPermissionAccess = true;
if (mPresenter != null) {
totalDistTravelled = mPresenter.getTrackDistanceTravelled();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart Started SHREDPREF totalDistTravelled="+String.valueOf(countForTrackPoints),"abcDistance.txt");
dist_travelled = mPresenter.getTrackDistanceCalculated();
}
buildGoogleApiClient();
/*locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);*/
bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee, pollFrequency);
requirementsOfListFragment = new Intent(CustomersInListFragment.GET_UPDATED_LOCATION_INFO);
requirementsOfMapFragment = new Intent(CustomersOnMapFragment.GET_UPDATED_LOCATION_INFO);
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onStart after buildGoogleApiClient called=" + totalDistTravelled, "abc.txt");
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(3000);
mLocationRequest.setFastestInterval(3000 / 2);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mGoogleApiClient.connect();
}
public void sendTrackedPointsToRemoteLoc(String initiatedScreenLocal) {
//Toast.makeText(SuprabhatApplication.getInstance(), "sendTrackedPointsToRemoteLoc called " + CommonUtils.getCurrentDateInYYYYMMDDFormat(), Toast.LENGTH_SHORT).show();
initiatedScreen = initiatedScreenLocal;
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPointsToRemoteLoc called InitiatedScr=" + initiatedScreenLocal + " totalDistTravelled=" + totalDistTravelled, "abc.txt");
if (allowNetworkCall) {
ArrayList<LatLngHolder> latLngHolderArrayList = new ArrayList<>();
ArrayList<LatLngHolder> trackedPoints = mPresenter.getAllFSRTrackedRecords(currentDate);
if (trackedPoints.size() > 0) {
trackStoredLocally = true;
latLngHolderArrayList.addAll(trackedPoints);
rls = trackedPoints.size();
}
if (presentLat != null && presentLon != null && !presentLat.isEmpty() && !presentLon.isEmpty()) {
if(countForTrackPoints > mPresenter.getTrackLastCount())
countForTrackPoints += 1;
else {
countForTrackPoints = mPresenter.getTrackLastCount();
countForTrackPoints += 1;
}
//dist_temp += 100;
LatLngHolder holder = new LatLngHolder(presentLat, presentLon, dist_travelled, speed_calculated, "", String.valueOf(countForTrackPoints), "Live");
//LatLngHolder holder = new LatLngHolder(presentLat, presentLon, String.valueOf(dist_temp), speed_calculated, "", String.valueOf(countForTrackPoints), "Live");
latLngHolderArrayList.add(holder);
if (latLngHolderArrayList.size() > 1) {
mPresenter.sendTrackedPoints(latLngHolderArrayList, initiatedBy);
} else if (latLngHolderArrayList.size() > 0) {
String strServerSentLattitude = mPresenter.getServerSentLattitude();
String strServerSentLongitude = mPresenter.getServerSentLongitude();
Double serverSentLatt,serverSentLong;
if (strServerSentLattitude ==null || strServerSentLongitude == null) {
serverSentLatt = currentLocation.getLatitude();
serverSentLong = currentLocation.getLongitude();
mPresenter.setServerSentLattitude(String.valueOf(serverSentLatt));
mPresenter.setServerSentLongitude(String.valueOf(serverSentLong));
mPresenter.sendTrackedPoints(latLngHolderArrayList, initiatedBy);
} else {
serverSentLatt = Double.parseDouble(mPresenter.getServerSentLattitude());
serverSentLong = Double.parseDouble(mPresenter.getServerSentLongitude());
float[] results = new float[1];
Location.distanceBetween(
serverSentLatt, serverSentLong,
currentLocation.getLatitude(), currentLocation.getLongitude(), results);
float difference = results[0];
/* mPresenter.sendTrackedPoints(latLngHolderArrayList,initiatedBy);
/* mPresenter.sendTrackedPoints(latLngHolderArrayList,initiatedBy);
previousLocation = currentLocation;*/
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints serverSentLatt="+serverSentLatt, "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints serverSentLong="+serverSentLong, "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints currentPosition.getLatitude()="+currentLocation.getLatitude(), "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints currentPosition.getLongitude()="+currentLocation.getLongitude(), "abc.txt");
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPoints calulated distanceDiff=" + difference, "abc.txt");
if (difference >= 40) {//40
mPresenter.setServerSentLattitude(String.valueOf(currentLocation.getLatitude()));
mPresenter.setServerSentLongitude(String.valueOf(currentLocation.getLongitude()));
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " InitiatingToHitServer>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + difference, "abc.txt");
mPresenter.sendTrackedPoints(latLngHolderArrayList, initiatedBy);
//preLatitude = currentLocation.getLatitude();
//preLongitude = currentLocation.getLongitude();
} else {
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " sendTrackedPointsToRemoteLoc distanceLesssThen40=" + initiatedScreenLocal + " totalDistTravelled=" + totalDistTravelled, "abc.txt");
countForTrackPoints -= 1;
}
//mPresenter.sendTrackedPoints(latLngHolderArrayList);
}
}
/*++init;
notificationBuilder.setContentText("i: " + init + " s: " + success + " f: " + fail + " dbs: " + dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId, notificationBuilder.build());*/
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
// n/w calls status illuminators
#Override
public void onSendingBulkTrackedPoints(FieldStaffPositionBackgroundPresenter.FieldNotesStartOrStopResultsCarrier resultsCarrier) {
int tempTrackedPointsStrd = mPresenter.getTrackLastCount();
if (tempTrackedPointsStrd < countForTrackPoints)
mPresenter.storeTrackCurrentCount(countForTrackPoints);
count++;
if (trackStoredLocally) {
//clear all local storage tracks
mPresenter.deleteAllFsrStoredTracks();
trackStoredLocally = false;
}
if (resultsCarrier.getStopLiveTracking().equalsIgnoreCase("Y")) {
mPresenter.storeTrackDistanceCalculated("0");
mPresenter.storeTrackDistanceTravelled(0f);
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
// this.stopSelf();
} else {
}
allowForAnotherTrackCall = true;
/*++success;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
#Override
public void onTrackPointsSendingError(String exception) {
mPresenter.storeTrackCurrentCount(countForTrackPoints);
mPresenter.storeFailedTrackInLocal(presentLat, presentLon, dist_travelled, speed_calculated, currentDate, mdformat.format(new Time(System.currentTimeMillis())), String.valueOf(countForTrackPoints));
//bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee,pollFrequency);
allowForAnotherTrackCall = true;
//FieldStaffPositionBackgroundTransmitter.writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onTrackPointsSendingError " + exception,"respnse.txt");
/*++fail;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
#Override
public void onTrackPointsSendingFailure(int statusCode, String message) {
mPresenter.storeTrackCurrentCount(countForTrackPoints);
mPresenter.storeFailedTrackInLocal(presentLat, presentLon, dist_travelled, speed_calculated, currentDate, mdformat.format(new Time(System.currentTimeMillis())), String.valueOf(countForTrackPoints));
//bulkLatLngThroughputManager.postDelayed(bulkLatLngThroughputEmployee,pollFrequency);
allowForAnotherTrackCall = true;
/*++fail;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
//FieldStaffPositionBackgroundTransmitter.writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " onTrackPointsSendingFailure " + message,"respnse.txt");
}
#Override
public void onLocalStorageOfTrackSuccess() {
/*++dbs;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
#Override
public void onLocalStorageOfTrackFailed(String exception) {
/*++dbf;
notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs+" dbf: "+dbf+" rls "+rls);
notificationManager.notify(notificationId,notificationBuilder.build());*/
}
public void writeDataToFile(String highestScore, String fileName) {
try {
// if (mPresenter.getFFAEnableLogging().equals("Y")) {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, fileName);
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
bw.write(String.valueOf(highestScore));
//bw.append(String.valueOf(highestScore));
bw.close();
// }
} catch (IOException e) {
e.printStackTrace();
}
}
//location related predefined helpers
#Override
public void onLocationChanged(Location location) {
if (location != null ) {
currentLocation = location;
requirementsOfListFragment.putExtra(CustomersInListFragment.PLOFS, presentLon);
requirementsOfListFragment.putExtra(CustomersInListFragment.DCFS, dist_travelled);
requirementsOfListFragment.putExtra(CustomersInListFragment.SCFS, speed_calculated);
requirementsOfListFragment.putExtra(CustomersInListFragment.TDTFS,totalDistTravelled);
LocalBroadcastManager.getInstance(this).sendBroadcast(requirementsOfListFragment);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLAFS, presentLat);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLOFS, presentLon);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.DCFS, dist_travelled);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.SCFS, speed_calculated);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLADFS,lat);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.PLODFS,lon);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.TDTFS,totalDistTravelled);
requirementsOfMapFragment.putExtra(CustomersOnMapFragment.CLBR,location.getBearing());
LocalBroadcastManager.getInstance(this).sendBroadcast(requirementsOfMapFragment);
//++dbs;
//notificationBuilder.setContentText("i: "+init+" s: "+success+" f: "+fail+" dbs: "+dbs);
//notificationManager.notify(notificationId,notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
}
/*#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
*//*Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);*//*
}*/
public void adamantForceCloseOfService()
{
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
if (bulkLatLngThroughputManager != null && bulkLatLngThroughputEmployee != null) {
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
}
/*if (locationManager!=null)
{
locationManager.removeUpdates(this);
}*/
if (notificationManager != null) {
notificationManager.cancel(notificationId);
}
// stopSelf();
}
#Override
public void onDestroy() {
/* writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " Service On onDestroyCalled", "abc.txt");
if (bulkLatLngThroughputManager != null && bulkLatLngThroughputEmployee != null) {
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
}
*//*if (locationManager!=null)
{
locationManager.removeUpdates(this);
}*//*
if (notificationManager != null) {
notificationManager.cancel(notificationId);
notificationManager.cancelAll();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.deleteNotificationChannel(channelId);
}
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
stopSelf();
super.onDestroy();*/
//stopSelf();
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " Service On onDestroyCalled", "abc.txt");
Log.i("onDestroy","onDestroy Called");
Intent broadcastIntent = new Intent(this, FieldStaffRestartBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
writeDataToFile("\n" + CommonUtils.getCurrentDateInDDMMYYYFormat() + " Service On onTaskRemoved called", "abc.txt");
Log.i("EXIT", "onTaskRemoved!");
Intent broadcastIntent = new Intent(this, FieldStaffRestartBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
//stoptimertask();
}
/* #Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (bulkLatLngThroughputManager != null && bulkLatLngThroughputEmployee != null) {
bulkLatLngThroughputManager.removeCallbacks(bulkLatLngThroughputEmployee);
}
*//*if (locationManager!=null)
{
locationManager.removeUpdates(this);
}*//*
if (notificationManager != null) {
notificationManager.cancel(notificationId);
notificationManager.cancelAll();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.deleteNotificationChannel(channelId);
}
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
stopSelf();
*//*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}*//*
}*/
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
I am testing in real Mobile device and I have tested in multiple devices mentioned below but in none the service onStartCommand was invoked after app was cleared from background.
Lenovo k7 power Android 7.0
Xiaomi Redmi 8A Dual Android 10 ( here i enabled Auto Start from setting privacy )
Moto G6 ( Android 9.0 )
Note : For Reference i have posted the service code that we are using. pls let me know why onStartCommand is not getting called after app was cleared from background.
I have written an android app which basically allows me to keep track of times and address of GPS coordinates.
I have 3 Lists each corresponding to Lyft, Uber and Other.
But I believe my app starts slowing down my Smart Phone (Samsung Galaxy S7 Edge, with Android O)
can someone look at my code and tell me why is it slowing my smart phone.
My assumption is that, possibly thread synchronization issue.
Attached is my code
1) MainActivity.java
package com.milind.myapp.gpstrackingservice;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.PowerManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AddressListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private PowerManager.WakeLock wakeLock;
private TextView labelAddress;
private TextView multiTextLyft;
private TextView multiTextUber;
private TextView multiTextOther;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
labelAddress = findViewById(R.id.label_address);
multiTextLyft = findViewById(R.id.multi_text_lyft);
multiTextUber = findViewById(R.id.multi_text_uber);
multiTextOther = findViewById(R.id.multi_text_other);
if (MyService.isServiceStarted())
{
MyService.getInstance().load(getSharedPrefs());
refreshAllViews();
}
PowerManager powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "myapp:My Lock");
}
#Override
protected void onStart()
{
super.onStart();
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WAKE_LOCK}, 1);
if (!MyService.isServiceStarted())
{
Intent intent = new Intent(this, MyService.class);
intent.setAction(MyService.ACTION_START_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
startForegroundService(intent);
}
else
{
startService(intent);
}
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
{
if (MyService.isServiceStarted())
{
MyService.getInstance().registerAddressListener(this);
}
wakeLock.acquire();
}
else
{
if (MyService.isServiceStarted())
{
MyService.getInstance().unregisterAddressListener(this);
}
wakeLock.release();
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults)
{
switch (requestCode)
{
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location loc)
{
final String address = MyService.getAddress(this, loc);
final CharSequence text = labelAddress.getText();
if (text.toString().equals(address))
{
return;
}
MyService.getInstance().load(getSharedPrefs());
labelAddress.setText(address);
refreshAllViews();
new Tone().play(880);
}
private void refreshAllViews()
{
runOnUiThread(new Runnable()
{
public void run()
{
refereshEditTextLyft();
refereshEditTextUber();
refereshEditTextOther();
}
});
}
private void refereshEditTextLyft()
{
multiTextLyft.setText(MyService.getInstance().getLyftAddresses());
}
private void refereshEditTextUber()
{
multiTextUber.setText(MyService.getInstance().getUberAddresses());
}
private void refereshEditTextOther()
{
multiTextOther.setText(MyService.getInstance().getOtherAddresses());
}
private SharedPreferences getSharedPrefs()
{
return getSharedPreferences("name", MODE_PRIVATE);
}
public void onLyftButtonClicked(View view)
{
MyService.getInstance().addLyftAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextLyft();
MyService.getInstance().save(getSharedPrefs());
}
public void onUberButtonClicked(View view)
{
MyService.getInstance().addUberAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextUber();
MyService.getInstance().save(getSharedPrefs());
}
public void onOtherButtonClicked(View view)
{
MyService.getInstance().addOtherAddress(labelAddress.getText());
new Tone().play(440);
refereshEditTextOther();
MyService.getInstance().save(getSharedPrefs());
}
public void onClearButtonClicked(View view)
{
if (MyService.isServiceStarted())
{
SharedPreferences sharedPreferences = getSharedPrefs();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
MyService.getInstance().clear();
refereshEditTextLyft();
refereshEditTextUber();
refereshEditTextOther();
}
}
public void onDelLyftButtonClicked(View view)
{
MyService.getInstance().delLyftEntry();
new Tone().play(440);
refereshEditTextLyft();
MyService.getInstance().save(getSharedPrefs());
}
public void onDelUberButtonClicked(View view)
{
MyService.getInstance().delUberEntry();
new Tone().play(440);
refereshEditTextUber();
MyService.getInstance().save(getSharedPrefs());
}
public void onDelOtherButtonClicked(View view)
{
MyService.getInstance().delOtherEntry();
new Tone().play(440);
refereshEditTextOther();
MyService.getInstance().save(getSharedPrefs());
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
public void onActionModeFinished(ActionMode mode)
{
super.onActionModeFinished(mode);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
}
2) The MyService.java
package com.milind.myapp.gpstrackingservice;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MyService extends Service implements LocationListener
{
private static final String TAG = MyService.class.getSimpleName();
public static final String ACTION_START_SERVICE = "ACTION_START_SERVICE";
public static final String ACTION_STOP_SERVICE = "ACTION_STOP_SERVICE";
public static final String ACTION_UBER = "ACTION_UBER";
public static final String ACTION_LYFT = "ACTION_UBER";
public static final String ACTION_END = "ACTION_END";
public static final String LYFT_PREFIX = "Lyft";
public static final String OTHER_PREFIX = "Other";
public static final String UBER_PREFIX = "Uber";
private static MyService mInstance = null;
private List<AddressListener> listeners = new ArrayList<>();
private List<AddressPoint> lyftAddresses = new ArrayList<>();
private List<AddressPoint> uberAddresses = new ArrayList<>();
private List<AddressPoint> otherAddresses = new ArrayList<>();
private Location mLastLocation;
public MyService()
{
super();
Log.d(TAG, "MyService(): constructor called");
}
public static boolean isServiceStarted()
{
Log.d(TAG, "isServiceStarted()");
return mInstance != null;
}
public static final MyService getInstance()
{
return mInstance;
}
#Override
public IBinder onBind(Intent intent)
{
Log.d(TAG, "onBind(Intent intent)");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand(Intent, flags, startId) : " + hashCode());
Log.d(TAG, "onStartCommand(...) intent=" + intent + "=" + ", flags=" + flags + ", startId=" + startId);
Log.d(TAG, "onStartCommand(...) isServiceStarted=" + isServiceStarted());
String action = null;
if (intent != null)
{
Log.d(TAG, intent.toString());
action = intent.getAction();
}
else
{
Log.d(TAG, "onStartCommand(...): early return");
return super.onStartCommand(intent, flags, startId);
}
if (isServiceStarted() == false && action == ACTION_START_SERVICE)
{
Log.d(TAG, "onStartCommand(...): Service starting=" + startId);
//startForegroundServivceNotification()
startRunningInForeground();
requestLocationUpdates();
mInstance = this;
Log.d(TAG, "onStartCommand(...): Service started=" + startId);
}
else if (isServiceStarted() == true && action == ACTION_STOP_SERVICE)
{
Log.d(TAG, "onStartCommand(...): Service stopping=" + startId);
stopLocationUpdates();
stopSelf();
Log.d(TAG, "onStartCommand(...): Service stop requested" + startId);
mInstance = null;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
Log.d(TAG, "onDestroy(): Service destroyed");
super.onDestroy();
mInstance = null;
}
private void stopLocationUpdates()
{
Log.d(TAG, "stopLocationUpdates()");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
private void requestLocationUpdates()
{
Log.d(TAG, "requestLocationUpdates()");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1500, 0, this);
Log.w(TAG, "requestLocationUpdates(): ended gracefully");
}
catch (SecurityException ex)
{
Log.w(TAG, "requestLocationUpdates(): Exception");
ex.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location)
{
Log.v(TAG, "onLocationChanged(Location location): started, location=" + location.toString());
dispatchLocationChange(location);
mLastLocation = location;
Log.v(TAG, "onLocationChanged: completed");
}
private void dispatchLocationChange(Location loc)
{
Log.v(TAG, "dispatchLocationChange(Location)");
for (AddressListener listener : listeners)
{
listener.onLocationChanged(loc);
}
}
public static String getAddress(Context context, Location loc)
{
Log.v(TAG, "getAddress(Location loc) started");
List<Address> addresses;
Geocoder gcd = new Geocoder(context, Locale.getDefault());
try
{
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
String strReturnAddress = "";
if (addresses != null && addresses.size() > 0)
{
final Address address = addresses.get(0);
Log.d(TAG, address.toString());
String addressLines = "";
Log.v(TAG, "Locale: " + address.getLocale());
for (int i = 0; i <= address.getMaxAddressLineIndex(); ++i)
{
Log.v(TAG, "AddressLine " + i + ": " + address.getAddressLine(i));
addressLines += address.getAddressLine(i) + ", ";
Log.v(TAG, "addressLines:" + addressLines);
}
String strAddress =
addressLines
;
Log.v(TAG, "strAddress:" + strAddress);
strReturnAddress = strAddress.substring(0, strAddress.length() - 2);
Log.v(TAG, "strReturnAddress:" + strReturnAddress);
}
Log.d(TAG, "getAddress(Location loc) completed with return=" + strReturnAddress);
return strReturnAddress;
}
catch (IOException e)
{
e.printStackTrace();
Log.d(TAG, "Exception", e);
}
Log.d(TAG, "getAddress(Location loc) completed with return=null");
return "";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.d(TAG, "onStatusChanged(provider, status, extras): status=" + status + ", extras=" + extras);
}
#Override
public void onProviderEnabled(String provider)
{
Log.d(TAG, "onProviderEnabled(provider) ");
}
#Override
public void onProviderDisabled(String provider)
{
Log.d(TAG, "onProviderDisabled(provider) ");
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private static void logGetProperties(final String tag, final Object obj)
{
Log.v(tag, "logGetProperties(...)");
Class cls = obj.getClass();
Method[] methods = cls.getMethods();
Log.v(tag, "methods.length = " + methods.length);
for (Method method : methods)
{
String methodName = method.getName();
Log.v(tag, "methodName = " + methodName);
if (methodName.startsWith("get")
&& (method.getParameters() == null || method.getParameters().length == 0)
&& method.getReturnType() != Void.class)
{
try
{
Log.v(tag, methodName + " = " + method.invoke(obj, new Object[0]));
}
catch (Exception ex)
{
Log.e(tag, methodName + " Failed (exception)");
}
}
}
}
public AddressListener registerAddressListener(AddressListener listener)
{
Log.d(TAG, "registerAddressListener(AddressListener)");
if (!listeners.contains(listener))
{
listeners.add(listener);
}
return listener;
}
public AddressListener unregisterAddressListener(AddressListener listener)
{
Log.d(TAG, "unregisterAddressListener(AddressListener)");
if (listeners.contains(listener))
{
listeners.remove(listener);
Log.d(TAG, "unregisterAddressListener(AddressListener): Listener removed");
return listener;
}
Log.d(TAG, "unregisterAddressListener(AddressListener): Listener not found");
return null;
}
public void addLyftAddress(CharSequence text)
{
Log.d(TAG, "addLyftAddress(CharSequence text): text: " + text);
lyftAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
public void addUberAddress(CharSequence text)
{
Log.d(TAG, "addUberAddress(CharSequence text): text: " + text);
uberAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
public void addOtherAddress(CharSequence text)
{
Log.d(TAG, "addOtherAddress(CharSequence text): text: " + text);
otherAddresses.add(new AddressPoint(System.currentTimeMillis(), text));
}
String getLyftAddresses()
{
return getAddresses(lyftAddresses);
}
String getUberAddresses()
{
return getAddresses(uberAddresses);
}
String getOtherAddresses()
{
return getAddresses(otherAddresses);
}
private String getAddresses(List<AddressPoint> addresses)
{
Log.d(TAG, "getAddresses(List<AddressPoint>)");
String strAddresses = "" + addresses.size() + "\n--------\n";
for (int i = 0; i < addresses.size(); ++i)
{
AddressPoint addresspoint = addresses.get(i);
strAddresses += addresspoint + "\n--------\n";
if ((i % 2) != 0)
{
strAddresses += "\n\n";
}
}
return strAddresses;
}
private void startRunningInForeground()
{
//if more than or equal to 26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
//if more than 26
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
{
String CHANNEL_ONE_ID = "Package.Service";
String CHANNEL_ONE_NAME = "Screen service";
NotificationChannel notificationChannel = null;
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null)
{
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle("Recording data")
.setContentText("App is running background operations")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(101, notification);
}
//if version 26
else
{
startForeground(101, updateNotification());
}
}
//if less than version 26
else
{
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("App")
.setContentText("App is running background operations")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setOngoing(true).build();
startForeground(101, notification);
}
}
private Notification updateNotification()
{
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
return new NotificationCompat.Builder(this)
.setContentTitle("Activity log")
.setTicker("Ticker")
.setContentText("app is running background operations")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setOngoing(true).build();
}
public void load(final SharedPreferences lSharedPrefs)
{
Log.w(TAG, "load(SharedPreferences): started");
load(lSharedPrefs, lyftAddresses, LYFT_PREFIX);
load(lSharedPrefs, uberAddresses, UBER_PREFIX);
load(lSharedPrefs, otherAddresses, OTHER_PREFIX);
Log.w(TAG, "load(SharedPreferences): completed");
}
private void load(final SharedPreferences lSharedPrefs, final List<AddressPoint> lAddrPoints, final String lPrefix)
{
Log.w(TAG, "load(SharedPreferences, lAddrPoints, lPrefix)");
lAddrPoints.clear();
final int count = lSharedPrefs.getInt(lPrefix + "Count", lAddrPoints.size());
for (int i = 0; i < count; ++i)
{
String address = lSharedPrefs.getString(lPrefix + "Address" + i, null);
final long time = lSharedPrefs.getLong(lPrefix + "Time" + i, 0);
//if address or time is invalid skip to the next entry
if (address == null || time == 0)
{
continue;
}
final AddressPoint addressPoint = new AddressPoint(time, address);
lAddrPoints.add(addressPoint);
}
}
private void save(final SharedPreferences lSharedPrefs, final List<AddressPoint> lAddrPoints, final String lPrefix)
{
Log.w(TAG, "save(SharedPreferences, lAddrPoints, lPrefix)");
SharedPreferences.Editor editor = lSharedPrefs.edit();
final int count = lAddrPoints.size();
//Save the count
editor.putInt(lPrefix + "Count", count);
for (int i = 0; i < count; ++i)
{
//Save the entry
AddressPoint lAddrPoint = lAddrPoints.get(i);
editor.putLong(lPrefix + "Time" + i, lAddrPoint.getTime());
editor.putString(lPrefix + "Address" + i, (String) lAddrPoint.getAddress());
}
Log.w(TAG, "save(sharedFrefs, List, String): commit");
editor.commit();
}
public void save(final SharedPreferences sharedPreferences)
{
Log.w(TAG, "save(SharedPreferences): started");
Log.w(TAG, "save: lyftAddresses");
save(sharedPreferences, lyftAddresses, LYFT_PREFIX);
Log.w(TAG, "save: uberAddresses");
save(sharedPreferences, uberAddresses, UBER_PREFIX);
Log.w(TAG, "save: otherAddresses");
save(sharedPreferences, otherAddresses, OTHER_PREFIX);
Log.w(TAG, "save(SharedPreferences) completed");
}
public void clear()
{
lyftAddresses.clear();
uberAddresses.clear();
otherAddresses.clear();
}
public void delLyftEntry()
{
if (lyftAddresses.size() > 0)
{
lyftAddresses.remove(lyftAddresses.size() - 1);
}
}
public void delUberEntry()
{
if (uberAddresses.size() > 0)
{
uberAddresses.remove(uberAddresses.size() - 1);
}
}
public void delOtherEntry()
{
if (otherAddresses.size() > 0)
{
otherAddresses.remove(otherAddresses.size() - 1);
}
}
}
3) activity_main.xml
4) AndroidManifest.xml
This (likely) isn't a threading issue, in the normal sense of the word. What's happening is you've got a GeoCoder.getFromLocation() call executing on the main thread. Per the documentation:
The returned values may be obtained by means of a network lookup. ...It may be useful to call this method from a thread separate from your primary UI thread.
That means the method could block for several seconds each time it is called. That's more likely if you're driving through an area of spotty cell coverage. Since the method is called with each location update (roughly every 2 seconds), it's understandable that the UI is hanging.
SUGGESTED FIX
Replace your getAddress() function with an AsyncTask, which moves the getFromLocation() call to a background thread (now your app will truly be multithreaded). Something like this should work:
private class GetFromLocationTask extends AsyncTask<Location, Void, List<Address>> {
protected List<Address> doInBackground(Location... locs) {
return gcd.getFromLocation(locs[ 0 ].getLatitude(), locs[ 0 ].getLongitude(), 1);
}
protected void onProgressUpdate(Void... progress) {}
protected void onPostExecute(List<Address> result) {
//execute the remainder of your getAddress() logic here
}
}
Then, execute it using new GetFromLocationTask().execute(location). Call this instead of getAddress(). You don't need to pass a Context to getAddress(), since Service.this will work just as well (it is a Context).
Bonus hint: Note that onLocationChanged() runs on the UI thread, and so does refreshAllViews(). That means your call to runOnUiThread() is superfluous, and it will just execute the given Runnable synchronously.
I saw some questions like this, but none of them solved my problem.
I'm starting a background service through an AlarmManager. Everytime the service starts, it checks if it has been disabled in SharedPreferences and, if not, it reschedule a new instance of itself and goes on, following these alternative paths:
if the user wants to use GPS, it waits for user's position and uses
it to call a REST endpoint;
if the user does not want to use GPS, it uses the position stored in prefs.
The result of the HTTP call (timeout: 30 seconds) is a JSONObject, which generates 0-n notifications (depending on how many "close objects" it finds).
My problem is: notifications, even if canceled by the user (sliding on them or opening them), often reappears, as if they were never shown. It should never happen, because the web service receives a list of excluded object ids that are updated every time.
Here the code:
ScannerService.java
package com.kiulomb.itascanner.service;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.kiulomb.itascanner.R;
import com.kiulomb.itascanner.network.HTTPRequestManager;
import com.kiulomb.itascanner.network.HTTPResponseListener;
import com.kiulomb.itascanner.network.URLs;
import com.kiulomb.itascanner.pref.FilterPreferencesManager;
import com.kiulomb.itascanner.pref.NotificationsHistoryManager;
import com.kiulomb.itascanner.pref.PrefConstants;
import com.kiulomb.itascanner.utils.Haversine;
import com.kiulomb.itascanner.utils.MyConfiguration;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class ScannerService extends Service {
private static final String TAG = ScannerService.class.getSimpleName();
private boolean locationFound = false;
private boolean withoutLocation = false;
private LocationManager mLocationManager = null;
private final Timer myTimer = new Timer();
private final long TIMEOUT = 20000;
TimerTask myTask = new TimerTask() {
public void run() {
try {
Log.i(TAG, "Timeout is over, trying to stop service (location found? " + locationFound + ")");
if (!locationFound) {
stopSelf();
}
} catch (Exception e) {
Log.e(TAG, "Could not stop service after time: " + e.getMessage());
}
}
};
private LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private boolean alreadySearching = false;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
LocationListener(String provider) {
Log.i(TAG, "LocationListener is " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(final Location location) {
Log.i(TAG, "onLocationChanged: " + location);
if (withoutLocation) {
return;
}
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (location != null) {
if (isConnected) {
mLastLocation.set(location);
locationFound = true;
Log.i(TAG, "already searching? " + alreadySearching);
if (!alreadySearching) {
findClosest(location.getLatitude(), location.getLongitude());
}
alreadySearching = true;
} else {
Log.e(TAG, "no connectivity, ending service");
stopSelf();
}
} else {
Log.e(TAG, "no position, ending service");
stopSelf();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, "onStatusChanged: " + provider);
}
}
private void initializeLocationManager() {
Log.d(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
// super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate");
SharedPreferences pref = getSharedPreferences(PrefConstants.PREF_APP_FILE, MODE_PRIVATE);
if (pref.getBoolean(PrefConstants.PREF_APP_SERVICE_ENABLED, PrefConstants.PREF_APP_SERVICE_ENABLED_DEFAULT)) {
Intent intent = new Intent(ScannerService.this, ScannerService.class);
PendingIntent pintent = PendingIntent.getService(ScannerService.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 60000, pintent); // or setExact() // TODO custom time
// alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60000, pintent);
if (!pref.getBoolean(PrefConstants.PREF_APP_SERVICE_CUSTOMCENTER, PrefConstants.PREF_APP_SERVICE_CUSTOMCENTER_DEFAULT)) {
// use GPS
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MyConfiguration.LOCATION_INTERVAL,
MyConfiguration.LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (SecurityException ex) {
Log.e(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.e(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MyConfiguration.LOCATION_INTERVAL,
MyConfiguration.LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (SecurityException ex) {
Log.e(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.e(TAG, "gps provider does not exist " + ex.getMessage());
}
} else {
withoutLocation = true;
// do not use GPS
String[] savedNotifCenter = pref.getString(PrefConstants.PREF_APP_SERVICE_CENTER, PrefConstants.PREF_APP_SERVICE_CENTER_DEFAULT).split(",");
double savedLat = Double.parseDouble(savedNotifCenter[0]);
double savedLng = Double.parseDouble(savedNotifCenter[1]);
locationFound = true; // prevent the service from stopping
findClosest(savedLat, savedLng);
}
} else {
stopSelf();
return;
}
/*if (isForeground(getPackageName())) {
Log.i(getClass().getSimpleName(), "application is in foreground, stopping service");
stopSelf();
return;
}*/
myTimer.schedule(myTask, TIMEOUT);
}
public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (LocationListener mLocationListener : mLocationListeners) {
try {
mLocationManager.removeUpdates(mLocationListener);
} catch (SecurityException se) {
Log.e(TAG, "security exception", se);
} catch (Exception ex) {
Log.e(TAG, "fail to remove location listeners, ignore", ex);
}
}
}
}
private void findClosest(final double lat, final double lng) {
new Thread(new Runnable() {
#Override
public void run() {
String url = URLs.buildURL(URLs.NOTIFICATIONS);
url += "?lat=" + lat;
url += "&lng=" + lng;
final SharedPreferences pref = getSharedPreferences(PrefConstants.PREF_APP_FILE, MODE_PRIVATE);
if (pref.contains(PrefConstants.PREF_APP_SERVICE_RADIUS)) {
url += "&radius=" + pref.getInt(PrefConstants.PREF_APP_SERVICE_RADIUS, PrefConstants.PREF_APP_SERVICE_RADIUS_DEFAULT);
}
url += "&limit=" + PrefConstants.PREF_APP_MAP_LIMIT_DEFAULT;
if (pref.contains(PrefConstants.PREF_APP_SERVICE_IV)) {
url += "&iv=" + pref.getInt(PrefConstants.PREF_APP_SERVICE_IV, PrefConstants.PREF_APP_SERVICE_IV_DEFAULT);
}
String exclusionsNumbers = getExcludedNumbersParam();
if (exclusionsNumbers.length() > 0) {
url += "&exNum=" + exclusionsNumbers;
}
final NotificationsHistoryManager notificationsHistoryManager = new NotificationsHistoryManager(ScannerService.this);
final List<Long> excludedIds = notificationsHistoryManager.getAlreadyFoundObjects();
String exclusionsIds = getExcludedIdsParam(excludedIds);
if (exclusionsIds.length() > 0) {
url += "&exId=" + exclusionsIds;
}
/*final long lastId = pref.getLong(PrefConstants.PREF_SERVICE_LAST_ID, 0L);
url += "&li=" + lastId;*/
final Context context = ScannerService.this;
HTTPRequestManager requestManager = new HTTPRequestManager(context, url, true, null, new HTTPResponseListener() {
#Override
public void onSuccess(JSONObject response) {
try {
JSONArray responseArray = response.getJSONArray("objects");
final String foundString = getString(R.string.found);
final String inCityString = getString(R.string.in_city);
final String expiringString = getString(R.string.expiring);
final DateFormat sdf = SimpleDateFormat.getTimeInstance();
final Resources res = getResources();
final String packageName = getPackageName();
final String mapsApiKey = getString(R.string.google_maps_key);
final boolean notifClickAutoCancel = pref.getBoolean(PrefConstants.PREF_APP_SERVICE_NOTIFCANCEL, PrefConstants.PREF_APP_SERVICE_NOTIFCANCEL_DEFAULT);
final boolean notifExpiredAutoCancel = pref.getBoolean(PrefConstants.PREF_APP_SERVICE_NOTIFCANCELEXPIRED, PrefConstants.PREF_APP_SERVICE_NOTIFCANCELEXPIRED_DEFAULT);
final boolean mapPicture = pref.getBoolean(PrefConstants.PREF_APP_SERVICE_MAPPICTURE, PrefConstants.PREF_APP_SERVICE_MAPPICTURE_DEFAULT);
final Locale defaultLocale = Locale.getDefault();
Calendar calendar = Calendar.getInstance();
// long maxId = lastId;
for (int i = 0; i < responseArray.length(); i++) {
try {
final MyEntity p = MyEntity.fromJSONLight(responseArray.getJSONObject(i));
// it should never happen, but notifications are shown many times :/
if (!excludedIds.contains(p.getId())) {
excludedIds.add(p.getId());
// maxId = Math.max(p.getId(), maxId);
final double iv = p.getIV();
final long expirationFixed = (p.getDisappearTime() - System.currentTimeMillis() - 2000);
final Calendar expirationTime = (Calendar) calendar.clone();
// now.add(Calendar.SECOND, (int) ((p.getDisappearTime() - System.currentTimeMillis() / 1000) - 2));
expirationTime.setTimeInMillis(expirationTime.getTimeInMillis() + expirationFixed);
final int distance = (int) Math.round(1000 * Haversine.distance(lat, lng, p.getLatitude(), p.getLongitude()));
String cityName = null;
Geocoder gcd = new Geocoder(context, defaultLocale);
List<Address> addresses = gcd.getFromLocation(p.getLatitude(), p.getLongitude(), 1);
if (addresses.size() > 0) {
cityName = addresses.get(0).getLocality();
}
final String cityNameParam = cityName;
new Thread(new Runnable() {
#Override
public void run() {
sendNotification((int) (p.getId()),
foundString + " " + p.getName() + (iv > 0 ? " " + iv + "%" : "") + (cityNameParam != null ? " " + inCityString + " " + cityNameParam : ""),
expiringString + " " + sdf.format(expirationTime.getTime()) + " - " + distance + "m" + (movesStringParam != null ? " (" + movesStringParam + ")" : ""),
p,
res,
packageName,
notifClickAutoCancel,
notifExpiredAutoCancel,
expirationFixed,
mapsApiKey,
mapPicture);
}
}).start();
}
} catch (Exception e) {
Log.e(TAG, "error", e);
}
}
notificationsHistoryManager.saveAlreadyFoundObjects(excludedIds);
stopSelf();
} catch (Exception e) {
Log.e(TAG, "error in reading JSONArray", e);
stopSelf();
}
}
#Override
public void onError(int errorCode) {
stopSelf();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(requestManager);
}
}).start();
}
private String getExcludedNumbersParam() {
String exclusionsNumbers = "";
List<Integer> excludedNumbers = new FilterPreferencesManager(ScannerService.this).getNotificationsExcludedNumbers();
int sizeNumbers = excludedNumbers.size();
for (int i = 0; i < sizeNumbers; i++) {
exclusionsNumbers += excludedNumbers.get(i);
if (i < sizeNumbers - 1) {
exclusionsNumbers += ",";
}
}
return exclusionsNumbers;
}
private String getExcludedIdsParam(List<Long> excludedIds) {
String exclusionsIds = "";
int sizeIds = excludedIds.size();
for (int i = 0; i < sizeIds; i++) {
exclusionsIds += excludedIds.get(i);
if (i < sizeIds - 1) {
exclusionsIds += ",";
}
}
return exclusionsIds;
}
private Locale locale = Locale.getDefault();
private void sendNotification(final int notificationId,
final String title,
final String message,
final MyEntity entity,
final Resources res,
final String packageName,
final boolean autoClickCancel,
final boolean autoExpiredCancel,
final long expirationFromNow,
final String mapsApiKey,
final boolean mapPicture) {
final double entityLat = entity.getLatitude();
final double entityLng = entity.getLongitude();
Intent mapIntent = null;
try {
String urlAddress = "http://maps.google.com/maps?q=" + entityLat + "," + entityLng;
mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlAddress));
} catch (Exception e) {
Log.e(TAG, "error in notification intent preparation", e);
}
PendingIntent pendingIntent = PendingIntent.getActivity(ScannerService.this, 0, mapIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
int drawable = res.getIdentifier("entity" + String.format(locale, "%04d", entity.getNumber()) + "big", "drawable", packageName);
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ScannerService.this)
.setSmallIcon(drawable)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(autoClickCancel)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_HIGH)
.setLights(ContextCompat.getColor(ScannerService.this, R.color.colorPrimary), 500, 2000);
if (mapPicture) {
String imageUrl = "https://maps.googleapis.com/maps/api/staticmap"
+ "?center=" + entityLat + "," + entityLng
+ "&zoom=14"
+ "&scale=false"
+ "&size=450x275"
+ "&maptype=roadmap"
+ "&key=" + mapsApiKey
+ "&format=jpg"
+ "&visual_refresh=true";
Log.i(getClass().getSimpleName(), "generated url for notification image: " + imageUrl);
Bitmap bmURL = getBitmapFromURL(imageUrl);
if (bmURL != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bmURL));
}
}
if (mapIntent != null) {
notificationBuilder.setContentIntent(pendingIntent);
}
if (autoExpiredCancel) {
Log.i(getClass().getSimpleName(), "setting notification timer for expiration, id: " + notificationId + ", expiring in " + expirationFromNow + "ms");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Log.i(getClass().getSimpleName(), "canceling notification expired, id: " + notificationId);
notificationManager.cancel(notificationId);
}
}, expirationFromNow);
}
}
// }
private Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
Notifications history manager
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class NotificationsHistoryManager {
private final static String PREF_FILE = "nh";
private final static String PREF_FOUND_KEY = "f";
private SharedPreferences pref;
public NotificationsHistoryManager(Context context) {
pref = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
}
public void saveAlreadyFoundObjects(List<Long> found) {
Set<String> idsString = new HashSet<>();
int size = found.size();
for (int i = Math.max(0, size - 200); i < size; i++) {
long f = found.get(i);
idsString.add(f + "");
}
pref.edit().putStringSet(PREF_FOUND_KEY, idsString).apply();
}
public List<Long> getAlreadyFoundObjects() {
List<Long> excluded = new ArrayList<>();
for (String id : pref.getStringSet(PREF_FOUND_KEY, new HashSet<String>())) {
try {
excluded.add(Long.parseLong(id));
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "error in parsing string '" + id + "' to long id: " + e.getMessage());
}
}
return excluded;
}
public void clean() {
pref.edit().clear().apply();
}
}
Note: when MainActivity is started, it checks if an instance of the service is running and, if not, it schedules a new one with an AlarmManager. I thought it was the cause of the problem, but the service, as you see, checks every time what has already been notified and skip it.
I tried changing START_STICKY to NOT_STICKY, using preferences to handle duplicate IDs, synchronizing operations... I don't know what else to try. Please, help me :) If you need any more details, just ask.
Thank you!
To share what I found... I understood what the problem is.
Take a look at NotificationsHistoryManager: it uses, to save the list of found object, a Set (the only "list" object type available in SharedPreferences), saving only the last 200 objects found (old ones expires, so it is meaningless to keep them).
THE PROBLEM IS: SET ARE NOT ORDERED LIST. The 200 objects I save are not the LAST added, because when I read them from pref (getAlreadyFoundObjects()) they are written in a set, "randomly" ordered.
I had to change the way I stored them, creating a custom string (comma separated values), to be sure they are saved in the order I want.
Hope it helps someone.
I am creating an android application that consists of printing data from printer connected via usb. Here, I want to set page layouts such as new line printing when reached at the end of page and page borders etc. Is it possible via programatically. Please help me how to do this.
This is what i had done for printing for data:
public class DemoPrinter extends Activity {
private final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
Button create_file;
PendingIntent mPermissionIntent;
UsbManager usbManager;
UsbDevice device;
EditText print_text;
UsbDevice printer = null;
private static final int PRINTER_VENDOR_ID = 1256;
private String filename = "MySampleFile.txt";
private String filepath = "PanelFilesstorage";
File myInternalFile;
String data= "This is a sample text";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_demo_printer);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
print_text = (EditText)findViewById(R.id.editText_printer);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList.size() <= 0)
{
Toast.makeText(getApplicationContext(), "Info: No device found", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "No of devices"+deviceList.size(), Toast.LENGTH_SHORT).show();
((TextView) findViewById(R.id.textView_devices))
.setText("No of device : " + deviceList.size());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
int count = 0;
mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(ACTION_USB_PERMISSION), 0);
while (deviceIterator.hasNext()) {
count++;
device = deviceIterator.next();
Log.i("info", "Device No " + count + "........");
Log.i("info", "Vendor id : " + device.getVendorId());
Log.i("info", "Product id : " + device.getProductId());
Log.i("info", "Device name : " + device.getDeviceName());
Log.i("info", "Device class : " + device.getClass().getName());
Log.i("info", "Device protocol: " + device.getDeviceProtocol());
Log.i("info", "Device subclass : " + device.getDeviceSubclass());
if (device.getVendorId() == PRINTER_VENDOR_ID) {
printer = device;
break;
}
}
findViewById(R.id.button_print).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Info", "Print command given");
IntentFilter filter = new IntentFilter(
ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (printer != null) {
usbManager.requestPermission(printer,
mPermissionIntent);
} else {
Log.e("Exception", "Printer not found");
}
}
});
} catch (Exception e) {
Log.e("Exception", "Exception in onCreate " + e.getMessage());
e.printStackTrace();
}
findViewById(R.id.button_create_file).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
FileOutputStream fos = new FileOutputStream(myInternalFile+"\n");
fos.write(data.toString().getBytes());
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
try {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
final UsbDevice printerDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (printerDevice != null) {
Log.i("Info", "Device permission granted");
startPrinting(printerDevice);
}
}
else
{
Log.d("Debug", "permission denied for device "
+ printerDevice);
}
}
}
} catch (Exception e)
{
Log.e("Exception", "Exception in onRecieve " + e.getMessage());
e.printStackTrace();
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
new Handler().post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = usbManager.openDevice(printer);
conn.claimInterface(usbInterface, true);
String myStringData = print_text.getText().toString();
myStringData+="\n";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint,
myStringData.getBytes(),
myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " +transfered);
} catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
}