Start Service in background Service - java

Is it possible to start a service from a background service?
This only works when the application is open...
Intent service = new Intent(this, MyForegroundSerivce.class);
service.setAction(Constants.ACTION.START_ACTION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(service);
} else {
startService(service);
}
I don't really start the service, I only call it with an action to start something, when a push notification is received.

Please use this service:
Start Service
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(MainActivity.this, new Intent(MainActivity.this, ServiceBG.class));
} else {
startService(new Intent(MainActivity.this, ServiceBG.class));
}
Service Class
public class ServiceBG extends Service {
private static final String NOTIFICATION_CHANNEL_ID = "my_notification";
private static final long TIME_INTERVAL = 10000;
private Handler handlerThred;
private Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setOngoing(false)
.setSmallIcon(R.drawable.ic_notification)
.setColor(getResources().getColor(R.color.white))
.setPriority(Notification.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
startForeground(1, builder.build());
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service", "BGS > Started");
if (handlerThred == null) {
handlerThred = new Handler();
handlerThred.post(runnableThred);
Log.w("Service ", "BGS > handlerThred Initialized");
} else {
Log.w("Service ", "BGS > handlerThred Already Initialized");
}
return START_STICKY;
}
private Runnable runnableThred = new Runnable() {
#Override
public void run() {
Log.w("Service ", "BGS >> Running");
if (handlerSendLocation != null && runnableThred != null)
handlerSendLocation.postDelayed(runnableThred, TIME_INTERVAL);
}
};
#Override
public void onDestroy() {
Log.w("Service", "BGS > Stopped");
stopSelf();
super.onDestroy();
}
}
AndroidManifest.XML
<service
android:name=".ServiceBG"
android:enabled="true"
android:exported="true" />

Related

Android Java start service from fragment

i am facing issue to start a service from fragment on a button click.
below is overview of Service class
public class FtpServiceDownload1 extends Service {
IBinder mBinder = new LocalBinder();
static String LOG_TAG = "Background Service 001";
private Handler customHandler = new Handler();
private Handler checkServiceHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private long startTime = 0L;
public boolean isFtpConnected(){
if(ftpHelperObj!=null){
return ftpHelperObj.ftp.isConnected();
}
return false;
}
public FtpHelperObject ftpHelperObj;
//#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.e(LOG_TAG,"binded called");
return mBinder;
}
public class LocalBinder extends Binder {
public FtpServiceDownload1 getServerInstance() {
return FtpServiceDownload1.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TO DO WORK
return(START_NOT_STICKY);
}
String NOTIFICATION_CHANNEL_ID = "com.form.lasertrac.ftpquery";
String channelName = "My Background Service";
static Notification notification = null;
static NotificationChannel notificationChannel = null;
static NotificationManager notificationManager = null;
static NotificationCompat.Builder notificationBuilder = null;
int id = 1;
private void startMyOwnForeground(){
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher_lasertrac)
.setContentTitle("FTP Query in background.")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(id, notification);
}
void notifyNotification(String msg){
notificationBuilder.setContentText("FTP Check "+msg);
notificationBuilder.setContentTitle("FTP Check Service ");
Date d = Calendar.getInstance().getTime();
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(FunctionsHelper.onlyForTimeFormatterView.format(d)+" "+msg));
Notification notification = notificationBuilder.getNotification();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(id, notification);
}
}
and below code in my fragment to start service
btn_service_load_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent mIntent2 = new Intent(getContext(), FtpServiceDownload1.class);
getContext().bindService(mIntent2, mConnectionFtpQuery, getContext().BIND_AUTO_CREATE);
getContext().startService(mIntent2);
}
});
FtpServiceDownload1 mServiceFtpQueryService ;
boolean mBoundedFtpQuery ;
ServiceConnection mConnectionFtpQuery = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(getContext(), "Ftp Query Service is disconnected", Toast.LENGTH_LONG).show();
mBoundedFtpQuery = false;
mServiceFtpQueryService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(getContext(), "Ftp Query service started", Toast.LENGTH_LONG).show();
mBoundedFtpQuery = true;
FtpServiceDownload1.LocalBinder mLocalBinder = (FtpServiceDownload1.LocalBinder) service;
mServiceFtpQueryService = mLocalBinder.getServerInstance();
}
};
my purpose is to start some service for particular work and stop it after work done.
when i click to start service, my application hangs and doesn't respond, if i call this service from my MainActivity class like below, it works
#Override
protected void onStart() {
super.onStart();
Intent mIntent2 = new Intent(this, FtpServiceDownload1.class);
bindService(mIntent2, mConnectionFtpQuery, BIND_AUTO_CREATE);
startService(mIntent2);
}

How I can call BroadcastReceiver from intent service?

I am trying to call BroadcastReceiver from intent service but it is never called:
public class IntentServiceTest extends IntentService {
public IntentServiceTest() {
super("IntentServiceTest");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(#Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Brodcast brodcast;
brodcast = new Brodcast();
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(brodcast, intentFilter);
}
}
}
Here is my BroadcastReceiver:
public class Brodcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "BroadcastReceiver", Toast.LENGTH_SHORT).show();
String NOTIFICATION_CHANNEL_ID = "100";
String channelName = "My back";
NotificationChannel channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(channel);
}
BluetoothAdapter bluetoothAdapter;
ArrayList<String> arrayList;
BluetoothDevice device;
NotificationManagerCompat notificationManagerCompat;
notificationManagerCompat = NotificationManagerCompat.from(context);
arrayList = new ArrayList<>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!arrayList.contains(device.getName())) {
arrayList.add(device.getName());
if (arrayList.size() >= 0) {
Toast.makeText(context, "s", Toast.LENGTH_SHORT).show();
}
}
Intent i = new Intent(context, MainActivity3.class);
i.putExtra("noti", NOTIFICATION_CHANNEL_ID);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder n = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification notification = n.setOngoing(true)
.setSmallIcon(R.drawable.ss)
.setContentTitle(arrayList.size() + device.getName())
.addAction(R.drawable.as, "Action", pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("App running"))
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
notificationManagerCompat.notify(1 , notification);
}
}
}
I need to call broadcast every 20 min; can anyone help me?

android service always running and notify user when needed

I need a service to make a notification whenever the user is in a moving car.
I use ActivityRecognition to find out when the user is in a car.the issue is I need my service to run even when the app is destroyed or removed by the user.
I tried running the service on a different process but after a few minutes the service stops working.I also tried using foreground service but I had the same issue with that to.
this is my service class.
public class SpeedCheckerService extends Service {
private final String CHANNEL_ID = "my_channel";
private static SpeedCheckerService speedCheckerService;
private ActivityRecognitionClient mActivityRecognitionClient;
private boolean started = false;
Date lastNotification;
CountDownTimer countDownTimer;
Intent intent;
#Override
public void onCreate() {
createNotificationChannel();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
this.intent=intent;
countDownTimer = new CountDownTimer(99999999,1000 * 60 * 1) {
#Override
public void onTick(long l) {
recognizeActivity();
}
#Override
public void onFinish() {
countDownTimer.start();
}
}.start();
return START_STICKY;
}
String detectedActivitiesToJson(ArrayList<DetectedActivity> detectedActivitiesList) {
Type type = new TypeToken<ArrayList<DetectedActivity>>() {}.getType();
System.out.println(detectedActivitiesList.toString());
if ((detectedActivitiesList.size()>=1)&&(detectedActivitiesList.get(0).getType() == DetectedActivity.STILL) && (detectedActivitiesList.get(0).getConfidence()) >= 60){
if(lastNotification!=null){
Calendar calendar = Calendar.getInstance();
calendar.setTime(lastNotification);
calendar.add(Calendar.MINUTE,5);
Date newDate = calendar.getTime();
calendar.clear();
System.out.println(lastNotification.toString());
System.out.println(newDate.toString());
if(newDate.after(calendar.getTime()) == true)
return null;
}
speedCheckerService.makeNotification();
lastNotification = Calendar.getInstance().getTime();
}
return new Gson().toJson(detectedActivitiesList, type);
}
public void makeNotification() {
createNotificationChannel();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("title")
.setContentText("text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.mapbox_logo_icon)
.setColor(Color.parseColor("#00ff00"))
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(70, builder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "guardian";
String description = "alerting user";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void recognizeActivity() {
if((mActivityRecognitionClient==null)&&(!started))
{
mActivityRecognitionClient = new ActivityRecognitionClient(this);
mActivityRecognitionClient.requestActivityUpdates(0, PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
started = true;
}
speedCheckerService =this;
if(ActivityRecognitionResult.hasResult(intent))
{
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
detectedActivitiesToJson(detectedActivities);
}
}
}
I would greatly appreciate if you can help me with my problem
Use foreground service instead of normal service and do the below changes
public class SampleService extends Service {
private NotificationManager mNotificationManager;
/**
* The identifier for the notification displayed for the foreground service.
*/
private static final int NOTIFICATION_ID = 1231234;
static void startService(Context context, String message) {
Intent startIntent = new Intent(context, SampleService.class);
startIntent.putExtra("inputExtra", message);
ContextCompat.startForegroundService(context, startIntent);
}
static void stopService(Context context) {
Intent stopIntent = new Intent(context, SampleService.class);
context.stopService(stopIntent);
}
private void createNotificationChannel() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = "Sample Notification";
// Create the channel for the notification
NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name,
NotificationManager.IMPORTANCE_DEFAULT);
mChannel.setSound(null, null);
// Set the Notification Channel for the Notification Manager.
notificationManager.createNotificationChannel(mChannel);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("Service", "onCreate");
createNotificationChannel();
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Service", "onStartCommand");
startForeground(NOTIFICATION_ID, getNotification(message);
**// This is important, When your service got killed it will try to restart //the service. But some android vendor phones are restricted this autostart**
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("Service", "onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
private Notification getNotification(String contentMessage) {
String title = getString(R.string.notification_title,
DateFormat.getDateTimeInstance().format(new Date()));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
NOTIFICATION_CHANNEL_ID).setContentTitle(title).setContentText(contentMessage)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setTicker(contentMessage)
.setAutoCancel(false)
.setWhen(System.currentTimeMillis());
return builder.build();
}
/**
* Returns true if this is a foreground service.
*
* #param context The {#link Context}.
*/
public boolean serviceIsRunningInForeground(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
Integer.MAX_VALUE)) {
if (getClass().getName().equals(service.service.getClassName())){
if (service.foreground){
return true;
}
}
}
return false;
}
}
You should use Foreground Service if you want service running even your app is in background or closed
https://androidwave.com/foreground-service-android-example/

Location Listener is not running my onLocationChanged

My buildLocationEvent(location) in onLocationChanged never runs? Is there a particular reason why this would be? I can see no reason, perhaps I am missing somethig obvious, please advise me what is going wrong here and how i can sort this so i can start to get the location data out properly.
I have copied the code below:
public class LService extends Service {
public static final String TAG = "Lervice";
private LocationListener listener;
private LocationManager manager;
private static LocationEvent locationEvent = new LocationEvent();
#RequiresApi(api = Build.VERSION_CODES.O)
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
super.onCreate();
startMyOwnForeground();
listener = new LocationListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onLocationChanged(Location location) {
buildLocationEvent(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
manager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, listener);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "com.app.myapp";
String channelName = "LService";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.GREEN);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(3, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
if(manager != null){
manager.removeUpdates(listener);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void buildLocationEvent(Location location){
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
double[] coordinate = {latLng.latitude, latLng.longitude};
locationEvent.setCoordinate(coordinate);
locationEvent.setAltitude(location.getAltitude());
locationEvent.setHorizontalAccuracy(location.getAccuracy());
locationEvent.setVerticalAccuracy(location.getVerticalAccuracyMeters());
locationEvent.setTimestamp(location.getTime());
sendLocationToManager(locationEvent);
}
private void sendLocationToManager(LocationEvent locationEvent){
Intent intent = new Intent("locationCreated");
sendLocalBroadcastEvent(intent, locationEvent);
}
private void sendLocalBroadcastEvent(Intent intent, LocationEvent locationEvent){
intent.putExtra("locationevent", locationEvent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
Thank you for your help on this. If you need anything clarifying please let me know.
Permissions are called in Main when i run:
String[] appPermissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
};
private static final int PERMISSIONS_REQUEST_CODE = 1240;
//get permissions for location
Log.d(TAG, "permissions: "+ checkAndRequestPermissions()); //false
if(true) {
//I RUN MY CODE HERE
}
}
private boolean checkAndRequestPermissions() {
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions) {
if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(perm);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
PERMISSIONS_REQUEST_CODE
);
return false;
}
//All Permissions granted
return true;
}
Hope that helps.
This is how i start the service:
public void startUpdatingLocation(){
//Start sensor service
Intent locationIntent = new Intent(MyApplication.getAppContext(), LService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MyApplication.getAppContext().startForegroundService(locationIntent);
} else {
MyApplication.getAppContext().startService(locationIntent);
}
}

Some Times Location Service is not working in background

I used Location Service in my android application, which extends Service and implements the GoogleApiClient, LocationListener. I am updating location onLocationChanged() method and my loaction update interval is 20 second. Sometimes Location Service is not working even though the app is in the background. I want to run my location service always anyhow. Each and every version of Android & every mobile, even though the app is killing from background also.
I call location service using AlarmManager also.
I gave call for location update in onStartCommand() method .
If location service is stopped then it will go to the onDestroy() method or onTaskRemoved() method in that method again I am calling startLocation method like,
startService(new Intent(this, LocationService.class));
My manifest code for service:
<service
android:name=".LocationService"
android:enabled="true"
android:stopWithTask="false"
/>
you can create location service like below.which run on background and foreground mode
public class ServiceLocation extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_location";
private static final long TIME_INTERVAL_GET_LOCATION = 1000 * 5; // 1 Minute
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 7; // meters
private Handler handlerSendLocation;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 5000;
Location locationData;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(TIME_INTERVAL_GET_LOCATION) // 3 seconds, in milliseconds
.setFastestInterval(TIME_INTERVAL_GET_LOCATION); // 1 second, in milliseconds
mContext = this;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setOngoing(false)
.setSmallIcon(R.drawable.ic_notification)
.setColor(getResources().getColor(R.color.fontColorDarkGray))
.setPriority(Notification.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
startForeground(1, builder.build());
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service Update Location", "BGS > Started");
if (handlerSendLocation == null) {
handlerSendLocation = new Handler();
handlerSendLocation.post(runnableSendLocation);
Log.w("Service Send Location", "BGS > handlerSendLocation Initialized");
} else {
Log.w("Service Send Location", "BGS > handlerSendLocation Already Initialized");
}
return START_STICKY;
}
private Runnable runnableSendLocation = new Runnable() {
#Override
public void run() {
// You can get Location
//locationData and Send Location X Minutes
if (locationData != null) {
Intent intent = new Intent("GPSLocationUpdates");
intent.putExtra("Latitude", "" + locationData.getLatitude());
intent.putExtra("Longitude", "" + locationData.getLongitude());
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
Log.w("==>UpdateLocation<==", "" + String.format("%.6f", locationData.getLatitude()) + "," +
String.format("%.6f", locationData.getLongitude()));
Log.w("Service Send Location", "BGS >> Location Updated");
}
if (handlerSendLocation != null && runnableSendLocation != null)
handlerSendLocation.postDelayed(runnableSendLocation, TIME_INTERVAL_GET_LOCATION);
}
};
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
locationData = locationResult.getLastLocation();
}
}, null);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity) mContext;
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.i("", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
Log.w("==>UpdateLocation<==", "" + String.format("%.6f", location.getLatitude()) + "," + String.format("%.6f", location.getLongitude()));
locationData = location;
}
#Override
public void onDestroy() {
if (handlerSendLocation != null)
handlerSendLocation.removeCallbacks(runnableSendLocation);
Log.w("Service Update Info", "BGS > Stopped");
stopSelf();
super.onDestroy();
}
}
Declare this service in android manifest file like below
<service
android:name=".ServiceLocation"
android:enabled="true"
android:exported="true" />
you can start service from activity using this code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(MainActivity.this, new Intent(MainActivity.this, ServiceLocation.class));
} else {
startService(new Intent(MainActivity.this, ServiceLocation.class));
}

Categories

Resources