Background service work instead the main activity - android

I am have main activity (to-do list application) that also call to background Service and this Service call to some GooglePlacesActivity class. the problem is when the Service is on the application go to the GooglePlacesActivity instead of doing this activity in the background and do the main activity as it should to do.
I will be happy if you can explain to me why this is happened and how I can fix this problem.
( I have two activities and one service. the main activity need to work in the front and the service need to call to the second activity and do the second activity in the background )
Background Service -
public class BackgroundProcess extends Service {
public GooglePlacesActivity PlacesActivity;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Intent in=new Intent().setClass(BackgroundProcess.this,GooglePlacesActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);
return START_STICKY;
}
}

Related

How to dismiss progress dialog from service?

I have an activity and it shows progress dialog when the user starts download
And the download from ftp start in a service
I want to dismiss this progress dialog when the service finishes downloading file
How to dismiss it from service?
A better approach would be to use LocalBroadcastManager for notifying Activity from Service.
Step1: Send the local broadcast from your service
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do your operation here(create worker thread for blocking operations)
sendLocalBroadCast() //call this method as soon as above operations completes
return Service.START_NOT_STICKY;
}
}
private void sendLocalBroadCast() {
Intent intent = new Intent("MY_SERVICE_NOTIFICATION");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Note that the system calls onStartCommand(Intent intent, int flags, int startId) on your service's main thread. A
service's main thread is the same thread where UI operations take
place for Activities running in the same process. You should always
avoid stalling the main thread's event loop. When doing long-running
operations, network calls, or heavy disk I/O, you should kick off a
new thread, or use AsyncTask
Step2: Make your Activity listen to this broadcast
public class MyActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// you can dismiss your progress dialog here. This method will be called when we receive broadcast from service after the service operation is completed
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
//register for listening to "MY_SERVICE_NOTIFICATION" event
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("MY_SERVICE_NOTIFICATION"));
}
#Override
protected void onDestroy() {
super.onDestroy();
// remove the receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}
}
Create an interface finishListener which has listen method, implement it in the activity to do whatever you want and pass it to the service constructor from there call listen method
Its simple
alertdialog.dismiss();
just put that in the bottom of your install code

Proper way to start activity in background

I need to do a logout after some time, so I'm opening the login window in my app using.
startActivity(intent);
Problem is that, if the user has my app in the background, my activity will pop up.
Is there a way to easily open an activity but keep my app in the background?
It can be done with Android appliaction component Service.
you can read about it in official documentation by links below.
https://developer.android.com/training/run-background-service/create-service#java
https://developer.android.com/guide/components/services?hl=en
Initialize your Service
public class MyBackgroundService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
//onCreate - Service created
}
#Override
public void onDestroy() {
//onDestroy - Service destroyed (Stopped)
}
#Override
public void onStart(Intent intent, int startid) {
//onStart - Service started
}
}
Then call Service in your Main Activity
startService(new Intent(this, MyBackgroundService.class));
And don't forget about declare in Manifest.
<service android:enabled="true"
android:name=".MyBackgroundService" />
You can implement "local logout" after some time and when user returns to activity you can detect it. More: https://developer.android.com/guide/components/activities/activity-lifecycle

Can't stop BluetoothAdapter started from background service

I have a service which is running in background process.This service is going to search for bluetooth devices after the application is killed by user.
<service android:name=".BLEBackgroundService"
android:enabled="true"
android:process=":externalBLEProcess"/>
in BLEBacgroundService class I have:
public class BLEBackgroundService extends Service{
.
.
.
public BLEDetector bleDetector;
public int onStartCommand(Intent intent, int flags, int startId) {
.
.
.
Log.i(tag,"onStartCommand");
startScan();
return START_STICKY;
}
void startScan() {
bleDetector.startScan();
Log.d(tag,"StartScan");
}
#Override
public void onDestroy() {
bleDetector.stopScan();
Log.w(tag,"Service OnDestroy");
super.onDestroy();
}
}
And in my BLEDetector class I have:
public class BLEDetector{
.
.
.
BluetoothAdapter mBAdapter;
public void stopScan(){
Log.i(tag,"StopScan");
mBAdapter.stopLeScan(stopCallback);
}
}
and in my activity here is how I start this service:
public class MyActivity extends AppCompatActivity{
Intent serviceIntent;
.
.
.
//This part is inside a Retrofit Callback onResponse
serviceIntent = new Intent(ItemListActivity.this,BLEBackgroundService.class);
serviceIntent.putExtra
(BasicUtils.getStringResource(getApplicationContext()
,R.string.beaconJsonIdentifier),new Gson().toJson(beaconModel));
serviceIntent.putExtra
(BasicUtils.getStringResource
(getApplicationContext(),R.string.currssiID), prgss);
if (BleUtil.isBluetoothEnabled(getApplicationContext()))
startService(serviceIntent);
}
public void disableService(){
stopService(serviceIntent);
}
And when I try to stop this service I just call disableService().
When I start service it calls onCreate successfully and service starts wroking on a seperate process which I can see logs from Logcat.But when I try to stop service it prints
Finally after reading this part of document I realized that sometimes my services onStartCommand function is called twice (which I have no idea why) and since I created bleDetector every time onStartCommand function was being called, I lost reference to it.
So all I had to do was to check to see if bleDetector was null or not.
How ever I have no idea why onStartCommand is being called multiple times.I call startService just once in my activity when I get a successful response from server using retrofit.
EDIT:
Sometimes in my activity, onResume is called multiple times and that's the reason why my startService is called multiple times.

The same background music playing in all activities

I use services to play background music in all activities and it works. The problem is the music continues playing even if my app is in background (when user exit with home button or back button). How can I solve this?
Services class BackgroundSoundService
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.slow_shock);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_NOT_STICKY;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Starting with
Intent svc = new Intent(this, BackgroundSoundService.class);
startService(svc);
Android Manifest:
<service android:enabled="true" android:name=".BackgroundSoundService" />
This is happened because the Service is still bounded in the activity. To terminate the service when multiple activity is bound to the service, you need to unbind the service from all of them as in the documentation says:
The service lifecycle—from when it's created to when it's
destroyed—can follow either of these two paths:
A started service
The service is created when another component calls startService().
The service then runs indefinitely and must stop itself by calling
stopSelf(). Another component can also stop the service by calling
stopService(). When the service is stopped, the system destroys it.
A bound service
The service is created when another component (a client) calls
bindService(). The client then communicates with the service through
an IBinder interface. The client can close the connection by calling
unbindService(). Multiple clients can bind to the same service and
when all of them unbind, the system destroys the service. The service
does not need to stop itself.
These two paths are not entirely separate. You can bind to a service
that is already started with startService(). For example, you can
start a background music service by calling startService() with an
Intent that identifies the music to play. Later, possibly when the
user wants to exercise some control over the player or get information
about the current song, an activity can bind to the service by calling
bindService(). In cases such as this, stopService() or stopSelf()
doesn't actually stop the service until all of the clients unbind.
Then call Context.stopService() to stop it:
context.stopService(new Intent(context, BackgroundSoundService.class));

Issue in calling Activity from the IntentService class

In my app, I am using the IntentService class to start another activity in the background. But the issue I got is that suppose from the IntentService class I start my activity, which opens my activity, after that I don't close my activity. Then I notice that when IntentService class again wants to start my same activity it is not called as the same activity is not close.
So, my question is: How can I start the same activity again and again whether it is open or close from the IntentService class?
Code in IntentService class
public class AlarmService extends IntentService
{
public void onCreate() {
super.onCreate();
}
public AlarmService() {
super("MyAlarmService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent) {
startActivity(new Intent(this,
AlarmDialogActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
use launchMode tag in manifest file
<activity
android:name=".ActivityName"
android:launchMode="singleTask" />
it will not create a different instance of activity if already available..
see this link launchMode for better understanding

Categories

Resources