I have a loop which do call to service:
context.startService(intent);
In and want to get back the result after the service finish its processing for each request. So I pass an unique id to intent to be able to distinguish the response.
But unfortunately, the startService which call to onStartCommand is not thread-safe. This leads to the response is always the last id, as the intent was changed in later call.
The service code is similar:
public class MyService extends Service {
protected Bundle rcvExtras;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
rcvExtras = intent.getExtras();
// Todo with information in rcv Extra
BaseRestClient restClient = new BaseRestClient(rcvExtras.getString(Constants.INTENT_KEY_OBJECT_TYPE));
restClient.post(data, rcvExtras.getString(Constants.INTENT_KEY_URL), new CallBackHandler(this)); // This is an async call
return super.onStartCommand(intent, flags, startId);
}
private class CallBackHandler extends Handler {
private final WeakReference<MyService> myServiceRef;
public CallBackHandler(MyService myService) {
myServiceRef = new WeakReference<>(myService);
}
#Override
public void handleMessage(Message msg) {
Intent result = new Intent(Constants.WS_CALL_BACK);
rcvExtras.putInt(Constants.INTENT_KEY_STATUS, msg.what);
result.putExtras(rcvExtras);
log.info("Broadcast data");
sendBroadcast(result); // Broadcast result, actually the caller will get this broadcast message.
MyService myService = myServiceRef.get();
log.info("Stopping service");
myService.stopSelf(startId);
}
}
}
How can I make service calling thread-safe?
I can see your problem, this is programatic issue not caused by framework. Here from you call startService until you call stopself, your MyService is singleton, and your rcvExtras is a global variable and will be shared between threads.
It is simple to fix:
Move the declaration of rcvExtras to method scope, here is onStartCommand.
Extend the CallBackHandler to allow your rcvExtras, and use it once callback.
At this time you do not have any varable can be shared, and you safe.
Hope this help.
Related
To know the difference between IntentService and Service in Android, I created the below posted small test of an IntentService class. The IntentService class can be started using
startService(intent); which will result in a call to nStartCommand(Intent intent, int flags, int startId). Also to send values from the IntentService class to the MainActivity
for an example, we should send it via sendBroadcast(intent); and the MainActivity should register a broadcastReceiver for that action so it can receive the values sent via
sendBroadcast(intent);
so far I cant see any difference between Service and IntentService!! Since they are similar in the way of starting them and the way they broadcast data,can you please tell me in
which context they differ?
please tell me why i am receiving those errors and how to solve it
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
private Button mbtnSend = null;
private int i = 0;
private BroadcastReceiver mBCR_VALUE_SENT = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(MyIntentService.INTENT_ACTION)) {
int intnetValue = intent.getIntExtra(MyIntentService.INTENT_KEY, -1);
Log.i(TAG, SubTag.bullet("mBCR_VALUE_SENT", "intnetValue: " + intnetValue));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(this.mBCR_VALUE_SENT, new IntentFilter(MyIntentService.INTENT_ACTION));
this.mbtnSend = (Button) findViewById(R.id.btn_send);
this.mbtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
intent.putExtra("intent_key", ++i);
startService(intent);
}
});
}
}
MyIntentService:
public class MyIntentService extends IntentService {
private final String TAG = this.getClass().getSimpleName();
public final static String INTENT_ACTION = "ACTION_VALUE_SENT";
public final static String INTENT_KEY = "INTENT_KEY";
public MyIntentService() {
super(null);
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
setIntentRedelivery(true);
}
#Override
public void onCreate() {
super.onCreate();
Log.w(TAG, SubTag.msg("onCreate"));
}
#Override
protected void onHandleIntent(Intent intent) {
Log.w(TAG, SubTag.msg("onHandleIntent"));
int intent_value = intent.getIntExtra("intent_key", -1);
Log.i(TAG, SubTag.bullet("", "intent_value: " + intent_value));
Intent intent2 = new Intent();
intent2.setAction(MyIntentService.INTENT_ACTION);
intent2.putExtra(MyIntentService.INTENT_KEY, intent_value);
sendBroadcast(intent2);
SystemClock.sleep(3000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, SubTag.msg("onStartCommand"));
return super.onStartCommand(intent, flags, startId);
}
In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.
From the docs:
Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Refer this doc - http://developer.android.com/reference/android/app/IntentService.html
Service
This is the base class for all services. When you extend this class, it’s important that you create a new thread in which to do all the service’s work, because the service uses your application’s main thread, by default, which could slow the performance of any activity your application is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don’t require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
Below are some key differences between Service and IntentService in Android.
1) When to use?
The Service can be used in tasks with no UI, but shouldn’t be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
2) How to trigger?
The Service is triggered calling to method onStartService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
for more clarity refer this
http://www.onsandroid.com/2011/12/difference-between-android.html
I'm trying to call a service class to update the value of a variable from my widget but it doesn't ever seem to get to the service class. I've had a look at some examples and I can't figure out what I'm doing wrong, and I don't really know very much about services yet. All help appreciated.
Service class
public class toggleMonitoringService extends Service{
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d("Me","creating service");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int startId, int something) {
// TODO Auto-generated method stub
String toggle = intent.getExtras().getString("Toggle");
Log.d("Me","Toggle : " + toggle);
if (toggle.equals("app1"))
{
UpdateWidgetService.monitorApp1 = !UpdateWidgetService.monitorApp1;
}
else if (toggle.equals("app2"))
{
UpdateWidgetService.monitorApp2 = !UpdateWidgetService.monitorApp2;
}
super.onStartCommand(intent, startId, something);
return 0;
}
}
Where I set up the intent and pending intent to handle the button click from the widget
Intent monitor1toggle = new Intent(this.getApplicationContext(),toggleMonitoringService.class);
monitor1toggle.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
monitor1toggle.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds);
monitor1toggle.putExtra("Toggle","app1");
PendingIntent monitor1 = PendingIntent.getService(getApplicationContext(), 0 , monitor1toggle,0);
remoteViews.setOnClickPendingIntent(R.id.firstappstatus, monitor1);
Try start service manually, wihtout using PendingIntent.
Better way is not to start service each time you need to do something, but to start it once, bind to it and use common method calls when you need something from the service.
For your example even a simple Thread would be more appropriate.
I created a Handler in my activity. The handler will be stored in the application object.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_activity);
appData = (AttachApplication) getApplication();
Handler updateHandler = new Handler() {
public void handlerMessage(Message msg) {
Log.d( TAG, "handle message " );
}
};
appData.setUpdateHandler( updateHandler );
}
My plan is that this handleMessage will be called when i setEmtpyMessage in my service. The service retrieves the handler from the application object.
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand of attachService");
List<Job> jobList = DBManager.getInstance().getAllOpenJobs();
appData = (AttachApplication) getApplication();
updateHandler = appData.getUpdateHandler();
updateHandler.sendEmptyMessage( 101 );
I checked the logs, but there is no handle message so that it seems that my plan does not work. I want to update a textfield each time my service did its job.
In Your case You shoild use BroadcastReceiver like this:
define receiver in your Activity class:
public class DataUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MainService.REFRESH_DATA_INTENT)) {
//do something
}
}
}
on your onCreate or onStart method you must register receiver:
DataUpdateReceiver dataUpdateReceiver = new DataUpdateReceiver();
IntentFilter intentFilter = new IntentFilter(MainService.REFRESH_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);
on your service add this:
public static final String REFRESH_DATA_INTENT = "done";
and when you done all staff you must send brocast like this:
sendBroadcast(new Intent(MainService.REFRESH_DATA_INTENT));
Your code snippet says public void handlerMessage(Message msg), but I think you mean public void handleMessage(Message msg), without the r. You can avoid these problems by using the #Override tag when you intent to override methods from a superclass; so your snippet would be rendered #Override public void handleMessage(Message msg), whereas #Override public void handlerMessage(Message msg) would be an error.
What are you trying to do? I really don't see the point of instantiating a Handler in an Activity, since all you're doing is getting Messages from the MessageQueue. You certainly don't want to fool around with any of the Messages that Android posts, and there are much better ways of sending messages to the Activity.
Of course, you don't include the code for AttachApplication, so I can only speculate.
You're also trying to access this Handler from a Service. Something is going on, but I'm not sure what.
If you want to update a TextView every time your Service does its job, send a broadcast Intent from the Service to the Activity, and use a broadcast receiver in the Activity. You should also consider using an IntentService instead of a Service.
seeing many questions about this but im unable to fix this.
I have this code
public class myBroadcastReceiver extends BroadcastReceiver {
private final String TAG = "myBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Consts.ANDROID_INTENT_ACTION_BOOT_COMPLEATE)){
Intent newinIntent = new Intent(context, ServiceBootCompleated.class);
context.startService(newinIntent);
}
}
}
It starts a Service and i can debug it using this line
android.os.Debug.waitForDebugger();
I see that return START_NOT_STICKY; is executed but still
the service is visible as a "running" service in the
Setttings>programs>Running Services
the onDestroy() is never called unless i stop it manually.
What do i have to do to stop it,
remove it from "Setttings>programs>Running Services " window?
Once you have completed the work you wanted to do in the background call stopSelf()
Be sure that any real work you do in the Service is done as a background thread and not in onCreate or onStartCommand.
See http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle for more details on the Service Lifecycle.
Example:
public int onStartCommand(final Intent intent, final int flags, final int startId)
{
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
//do work
stopSelf();
}
},"MyWorkerThread");
thread.start();
return Service.START_NOT_STICKY;
}
on completion of task, you have to do context.stopService() for stopping this type of unbound service.
Regards,
SSuman185
I have a method in a service that I created, and I want to access this method from an Activity that implements a Progress Dialog. This method simply update my database, and it was returning an ANR problem, so I created a Thread and in this thread I want to call this method that is in my Service. I tried instantiating the Service, but the object is null
So, how to create an 'object' in my activity where I can access this method. Someone could help me with that implementation??
Thanks.
The code:
public class UpdateDBProgressDialog extends Activity {
private String LOG_TAG = "UpdateDBProgressDialog";
private TextView tv;
private ProgressDialog pd;
private Handler handler;
private RatedCallsService rcs;
private Intent intent;
public boolean mIsBound = false;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
pd = ProgressDialog.show(this, "Updating Database", "The application is updating the database. Please wait.", true, false);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
}
};
Thread thread = new Thread(){
public void run() {
try{
rcs.updateDB();// Here I'm trying to call the method that is from the service class. But it says 'rcs' is null.
handler.sendEmptyMessage(0);
}catch(Exception e){e.printStackTrace();}
}
};
thread.start();
new Thread(){
public void run(){
try{
Thread.sleep(10000);
if(!RatedCallsService.RUNNING){
Intent i = new Intent(UpdateDBProgressDialog.this, RatedCallsService.class);
UpdateDBProgressDialog.this.startService(i);
}
}catch(Exception e){e.printStackTrace();}
}}.start();
}
}
I just want an object of the service so I can call the method I created there.
When you start or bind a Service its onCreate method calls and whenever you Start/Bind it again, its onStartCommand method will call. Because service is already created.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY)) // where ACTION_PLAY="any.unique.name.play"
processPlayRequest();
else if (action.equals(ACTION_PAUSE)) // where ACTION_PAUSE="any.unique.name.pause"
processPauseRequest();
else if (action.equals(ACTION_SKIP))
processSkipRequest();
else if (action.equals(ACTION_STOP))
processStopRequest();
else if (action.equals(ACTION_REWIND))
processRewindRequest();
else if (action.equals(ACTION_URL))
processAddRequest(intent);
return START_NOT_STICKY; // Means we started the service, but don't want
// it to
// restart in case it's killed.
}
And call it like:
Intent serviceIntent = new Intent(this, ServiceToStart.class);
serviceIntent.setAction("any.unique.name.play"); // onClick of play button
startService(serviceIntent);
If you want to invoke an operation on a Service from an Activity, there are two options. One is to create an Intent with any data set as extras on the Intent, and then start the Service kind of like you have done in the code. Then in the Service's onStartCommand, pull out the extras and invoke the appropriate method on your Service. For this option, you probably want to use an IntentService. The other option is to bind to the Service and directly invoke methods on it. To do this you will need to declare your Service's operations using AIDL. See the API documentation on Service for details.