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…
- when thread will stop?
- Then why we required services in android?
Thank You.
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.