29

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 ?

praveen
  • 291
  • 1
  • 3
  • 5
  • You should post the code you're trying to run so we can see exactly what you are doing. My guess is that the code you have in your service should be executed on a new thread. Please post the service you are trying to execute. – BlackHatSamurai Oct 24 '13 at 18:49

6 Answers6

9

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.

Community
  • 1
  • 1
Eugene
  • 656
  • 8
  • 20
2

All you are doing there is launching the new activity, so if your logic for running the monitor is in SensorService, then it's still going to be on the main thread. You need to put the monitoring logic into the new thread, not just launch the activity with it.

If you are trying to run a service on a background thread you need to use the static performOnBackgrounThread method like this code which can be found in the Android documentation (android-8\SampleSyncAdapter\src\com\example\android\samplesync\client\NetworkUtilities.java):

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {

            }
        }
    };
    t.start();
    return t;
}

It is also important to remember that you never want to perform network operations on the Main UI thread. Not that you have here, just a FYI...

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
2

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);
gowri
  • 681
  • 9
  • 27
2

To start service in the same process but another non-main thread, we can create another HandlerThread and use Handler for running our jobs on it.

class MyService : Service() {
    private lateinit var thread: HandlerThread
    private lateinit var handler: Handler

    override fun onCreate() {
        super.onCreate()
        thread = HandlerThread("MyService").apply {
            start()
        }
        handler = Handler(thread.looper)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent?.action == "my-job") {
            handler.post {
                // Do any job on another non-main thread here
                // ...
            }
        }
    }

    override fun onDestroy() {
        thread.interrupt()
        super.onDestroy()
    }
}
Pavel Shorokhov
  • 4,485
  • 1
  • 35
  • 44
1

I think the answer to this problem lies in the power of IntentService. IntentService is a subclass of the regular Service class. There are a few key differences, however.

Now, here's how you can take IntentServices to your advantage: IntentServices do not run on the main thread. Instead, they run on separate "Worker threads". This single attribute would solve your problem and eradicate the ANRs you are currently facing.

To learn more about the differences between services and IntentServices, check this out.

halfer
  • 19,824
  • 17
  • 99
  • 186
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
0

you can try using AsyncTask, please read this documentation.

http://developer.android.com/reference/android/os/AsyncTask.html

harsha.cs
  • 122
  • 2
  • 13
  • 1
    This didn't work for me; the service still seemed to run in the main thread despite the call to `startService` being done in a different thread. – Sam Nov 02 '14 at 02:38