user861973
user861973

Reputation: 777

android Thread and Service

I am using below code.

   import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract.Data;
import android.util.Log;

public class ActivityDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Thread(new Runnable() {

            @Override
            public void run() {
                int i=0;
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Log.i("DATA", "Data.CONTENT_TYPE......"+(i++));
                }

            }
        }).start();
    }
    @Override
    public void onBackPressed(){
        finish();
    }
}

When I press Back button of device still thread is working in background.

My questions are...

  1. when thread will stop?
  2. Then why we required services in android?

Thank You.

Upvotes: 1

Views: 208

Answers (2)

YshakPK
YshakPK

Reputation: 181

Services are basically used for performing long-running application on the background.If you are using any network operations or playing musing or something like that, services are very much helpful..

Upvotes: 1

Martin
Martin

Reputation: 4816

Answers: 1 - it will stop after 100 milliseconds 2 - you need something to work in the background like a service that wakes up and performs a function without there being a user to initiate it. Or you want to have a progressDialog that tells the user some work is happening rather than let the user assume the UI is frozen. Without the background service, your UI is left with an app that doesn't respond while the work is happening.

Upvotes: 1

Related Questions