Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android-How to run Service in different thread than main thread?

Tags:

I am trying to develop a application in android that consists a service to read the sensor value for multiple hours. When i start the service my device get hang and all the other process is got slow. To solve this problem i have try to startservice in separate thread as given below but problem is still there.

    new Thread(new Runnable() {                  @Override                 public void run() {                     Intent intent=new Intent(getApplicationContext(), SensorService.class);                     startService(intent);                  }             }).start(); 

this thread only start the service in different thread but service run in main thread. Plz someone help me how to run service in separate thread ?

like image 559
praveen Avatar asked Oct 24 '13 04:10

praveen


People also ask

How do I run a service from a different thread?

new Thread(new Runnable() { @Override public void run() { Intent intent=new Intent(getApplicationContext(), SensorService. class); startService(intent); } }). start(); this thread only start the service in different thread but service run in main thread.

Does service run on separate thread Android?

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.

Does service run on background thread?

Choosing between a service and a threadA service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.


2 Answers

Application components (services, activities, etc) always run in main thread, no matter what thread they are started from. Consider starting thread in your Service instead, or use an IntentService.

In your particular case you might try to register a global BroadcastReceiver for sensor changes, which, in turn,will start an IntentService to put newly acquired values in db, etc.

Actually, here is the link to similar question solved.

Again, this is not really a multithreading issue. The whole task must be implemented the other way.

like image 176
Eugene Avatar answered Sep 25 '22 05:09

Eugene


You can use Background Services to solve this problem. By using a Thread with sleep() for particular instance will give the solution to yours problem

Background Servies

This link Will help you..

Or Using of PendingIntent will help you, like...

PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, ij, Intent.FLAG_ACTIVITY_NEW_TASK); 
like image 42
gowri Avatar answered Sep 26 '22 05:09

gowri