Android Background Service and Thread - android

I am developing android application using rabbit mq pub/sub technology. I want to listen incoming message in android background service. Can I run thread in android background service ?
public class MessagingService extends Service {
private Thread subscribeThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
subscribeThread = new Thread(new Runnable() {
#Override
public void run() {
//Connecting to server and listen incoming message.
}
});
subscribeThread.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
subscribeThread.interrupt();
}
}

Yes you can run new thread in Android Service.
Please see note in documentation here: http://developer.android.com/guide/components/services.html
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.
Hope this will help you.

Related

How to keep a service alive in Flutter to run a socket io

I'm trying to create a service which will run a socket for receiver data when the app is closed.
According to this thread on Github Flutter should provide an abstraction for background execution, flutter doesn't have an abstraction that executes a code in the background, so I'm writing a native code.
The service opens up correctly, but as soon as the app is closed, it gets moved to cache services and after approximately 5 minutes it is ended.
I found this background_service MainActivity.java, but I'm not using the notification example contained in that repository. (The service contained in this repository also gets terminated once the app is closed.
The example plugin for this article as well.
I still don't have a concrete plan to make the socket connection in the service. I actually would like to call the socket_io_client function within the service, sort of like a callback, but I'm not sure if it will work.
So I just want to know if it is possible to keep the service running after the app is closed. If yes, how?
MainActivity.java
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "com.retroportalstudio.www.background_service";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent forService = new Intent(this, MyService.class);
forService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("startService")) {
startService(forService);
result.success("Service Started");
}
}
});
}
}
public class MyService extends Service {
// #Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return START_STICKY;
// }
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

Does FusedLocation updates work as background service?

I have a class for using FusedLocationApi to send the location of user frequently to the server. All methods for getting location updates and communicating with server are set in this class except that when I want to run this class, I call a background service and then use this class inside it.
Uisng FusedLocationApi.requestLocationUpdates , the location is being sent to the server properly and I can see Toasts from this service. But when I check the Running services on android system, my application is not listed there.
My question is that why my service is not running anymore but the location is being updated? Is the FusedLocation Service is a background service itself? Do I need to call it frequently through a background service to keep it alive or I can call it inside the activity and let it continue running even after closing the app?
this is how I use the class inside my own service:
public class LocationService extends Service {
FusedClass mylocation=new FusedClass(this);
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("turnOn")) {
HandlerThread handlerThread = new HandlerThread("LocationThread");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
#Override
public void run() {
mylocation.LocationStartPoint();
}
});
}
if (intent.getAction().equals("turnOff")) {
stopSelf();
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
EDIT: I use FusedLocationApi.requestLocationUpdates and onLocationChanged to get location updates from this API.

keeping a service running after shutting down the app

i'm trying to create an app that communicates with my localhost and search in a database.
I already make the connection and find the data, but i need to stay connected and send a notification if there's any changes in the table, but I can't figure it out how to keep the connection even when I close the app, because it closes everything, even the service.
The service doesn't stay open.
This is my Class:
public class SensorService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Starting",Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean bandera = true;
Toast.makeText(this, "Checking data...", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopService(new Intent(this,SensorService.class));
startService(new Intent(this,SensorService.class));
}
#Override
public void onDestroy() {
startService(new Intent(this,SensorService.class));
}
}
Every time I close the app, the service execute one more time and no more.
If you want the service to continue running after the app is closed, you need to call the startForeground(int, Notification) method from within the service. Android limits you to running longer running services in the background only as long as a notification is displayed to the user letting them know that a service is running (like a music player or a downloading service).
This is an intentional design constraint to ensure developers do not start services in the background that run indefinitely without the user being aware. Supply your own notification (can be anything) and you should be able to run the service in the background.
For more detailed information on this method, read it at: startForeground(int, Notification)
You can use onTaskRemoved and restart the service if needed.
#Override
public void onTaskRemoved(Intent rootIntent){
super.onTaskRemoved(rootIntent);
//restart your service
}
Please note that if you use onTaskRemoved, start your service as not sticky so it won't be restarted.
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_NOT_STICKY;
}

Background data collector in Android restarts when App is terminated

I want to collect accelerometer data with my app. Therefore I created a service, so the app collects the data in the background, even when the app is no longer open.
Problem is, that when I close the app, the service gets terminated as well and restarts. During that time it won't collect data.
I tried both START_REDELIVER_INTENT and START_STICKY, both with the same result: when the app closes, the service restarts.
Is there way to prevent the service completely from stopping when the app is terminated?
Note that my service is running in a separate process.
Here is my code:
#Override
public void onCreate() {
// start thread
HandlerThread thread = new HandlerThread("SensorData", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
looper = thread.getLooper();
handler = new BGHndlr(looper);
sensorMngr = (SensorManager) getSystemService(SENSOR_SERVICE);
reader = new SensorReader(sensorMngr);
accSensor = reader.getSingleSensorOfType(Sensor.TYPE_ACCELEROMETER);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message message = handler.obtainMessage();
message.arg1 = startId;
handler.sendMessage(message);
return START_REDELIVER_INTENT;
}
Nested class:
public class BGHndlr extends Handler implements SensorEventListener {
public BGHndlr(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
oSensorManager.registerListener(this, oAcceleroMeter, SensorManager.SENSOR_DELAY_FASTEST);
}
//int i = 0;
#Override
public void onSensorChanged(SensorEvent event) {
// do something
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {}
}
both with the same result: when the app closes, the service restarts.
This is a normal Android behavior, there is nothing an Android application developer can do about it.
Note that my service is running in a separate process.
Same as before (all in your question proves it)... That said, the answer to
Is there way to prevent the service completely from stopping when the app is terminated?
is No. You, as others, should stick to the Android components' lifecycle.

Stop the Service after the Vibrating the Phone in android?

I am trying to learn service in android.My goal is like that i will pass a LatLng Object to the service then service will do something with that and when the work will be finished then it will buzz the phone for sometime and stop.Finally the service will be finished.Now I have some query on that:
I will call the service from my app and user can close my app though
service is not finished.will service do the job initiated by my app or
it will also finish??
What i studied take me here that service will continue to execute and one thing i don't have to return anything back to activity who has initiated the service.I have written some code.Can anyone help me out??
public class MapService extends Service {
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
//here i will do my work
if(isRunning){
Log.i(TAG, "Service running");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
Will it work if user closes the app??
Yes this service will run even if user will close app.It is also possible if android system demands memory service will be stopped but it will restart again
as you have set your flag START_STICKY in your onStartCommand.
On Android KitKat and above(4.4+), the service will be stopped if user swipe kills the application and it won't be restarted by the system. See this discussion(1). If the application was stopped by Android system itself (for low resources), the service will be restarted after a while(use START_STICKY flag).
On Android 4.3 and below, service will be restarted irrespective of whether application was stopped by system or user(use START_STICKY flag).
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}

Categories

Resources