aman003 aman003 - 4 months ago 6
Android Question

Sometimes service get called and sometime it doesn't

I have an activity which stores some data (edittext and image) in database.
Service runs sometime and sometime it doesn't . I am taking the image for imageview plus some text data and passing it to the service which calls my database class. Why isn't the service getting called every time ??

passing data to service :

imgView = (ImageView)findViewById(R.id.imageView2);
if(imgView.getDrawable()==null) {
imageData = null ;
}
else {
Bitmap bitmap = ((BitmapDrawable) imgView.getDrawable()).getBitmap();
imageData = getBytes(bitmap);
}

Intent i = new Intent(this,TaskService.class);
i.putExtra("heading",s);
i.putExtra("subject",s1);
i.putExtra("date",s2);
i.putExtra("notes",s3);
i.putExtra("imageData",imageData);
startService(i);


and this is my service class :(TaskDatabaseClass this is my db class)

public class TaskService extends Service {

String s,s1,s2,s3;
byte[] imagedata;
public TaskService() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

s = intent.getStringExtra("heading");
s1 = intent.getStringExtra("subject");
s2 = intent.getStringExtra("date");
s3 = intent.getStringExtra("notes");
imagedata = intent.getByteArrayExtra("imageData");

Runnable r = new Runnable() {
@Override
public void run() {
try{
TaskDatabaseClass enterData = new TaskDatabaseClass(TaskService.this);
enterData.open();
enterData.createEntry(s,s1,s2,s3,imagedata);
enterData.close();
}catch(Exception e) {
}
}
};
Thread thread = new Thread(r);
thread.start();
this.stopSelf();
return 0;
}

@Override
public void onDestroy() {
Log.i(TAG ," destroying ");
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;

Answer

It seems you are doing a bit of database write operation in your Service. This seems redundant as Android services aren't suitable for these tasks (not that they would be useless). If you simply need to spawn a new thread then, you can call the same operation in a new thread (just like in your service) from even your Activity and it would be much efficient that current setup.

Doing this task in the Service not only creates a overhead on the Android system of creating a Service and maintaining its life-cycle, even you need to worry about data transfer via intents which is an additional overhead on the system.

You can read more about the uses of Services over here under the heading "What is Service".

Comments