The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks
package com.journaldev.androidintentservices;
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
String message = intent.getStringExtra("message");
intent.setAction(MainActivity.FILTER_ACTION_KEY);
SystemClock.sleep(3000);
String echoMessage = "IntentService after a pause of 3 seconds echoes " + message;
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent.putExtra("broadcastMessage", echoMessage));
}
}
package com.journaldev.androidintentservices;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
EditText editText;
MyReceiver myReceiver;
public static final String FILTER_ACTION_KEY = "any_key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
editText = findViewById(R.id.inputText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = editText.getText().toString();
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("message", message);
startService(intent);
}
});
}
private void setReceiver() {
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FILTER_ACTION_KEY);
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
@Override
protected void onStart() {
setReceiver();
super.onStart();
}
@Override
protected void onStop() {
unregisterReceiver(myReceiver);
super.onStop();
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("broadcastMessage");
textView.setText(textView.getText() + "
" + message);
}
}
}