프로그래밍언어/Java_Language
안드로이드 - 서비스
Great king
2019. 10. 29. 10:02
- 서비스를 시작시키기 위해 startService()메서드를 호출할 때는 인텐트 객체를 파라미터로 전달하며, 인텐트 객체는 어떤 서비스를 실행할 것인지에 대한 정보를 가지고 있다.
- 시스템은 서비스를 시작시킨 후 인텐트 객체를 서비스에 전달한다.
새로운 서비스 추가하기
프로젝트 영역에서 [우클릭] -> New -> Service -> Service 메뉴를 이용해 서비스 추가
My_Service 클래스 안에 마우스 커서를 둔 상태로 마우스 우클릭, 팝업 메뉴에서 [Generate -> Override Methods]
메인 액티비티 레이아웃 구성 (서비스 예제)
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText editText;
Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
btnSend = findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editText.getText().toString();
//인텐트 객체 만들고 부가 데이터 삽입
Intent intent = new Intent(getApplication(), MyService.class);
intent.putExtra("command", "show");
intent.putExtra("name",name);
//서비스 시작
startService(intent);
}
});
Intent passwdIntent = getIntent();
processIntent(passwdIntent);
}
@Override
protected void onNewIntent(Intent intent) {
//액티비티가 새로 만들어질 때 전달된 인텐트 처리
processIntent(intent);
super.onNewIntent(intent);
}
private void processIntent (Intent Intent){
if (Intent != null){
String command = Intent.getStringExtra("command");
String name = Intent.getStringExtra("name");
//토스트 메시지 출력
Toast.makeText(getApplicationContext(), "command : "+command +
", name: "+ ", name :" + name, Toast.LENGTH_LONG).show();
}
}
}
MyService.java
public class MyService extends Service {
private static final String TAG = "MyService";
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"onCreate() 호출됨");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand() 호출됨");
if (intent == null){
return Service.START_STICKY;
}else{ //인텐트 객체가 null이 아니면 processCommand()메소드 호출
processCommand(intent);
}
return super.onStartCommand(intent, flags, startId);
}
private void processCommand(Intent intent){
//인텐트 데이터 가져오기
String command = intent.getStringExtra("command");
String name = intent.getStringExtra("name");
//로그 띄우기
Log.d(TAG, "command: "+command+", name: "+name);
//5초동안 1초에 한번씩 로그 출력
for (int i=0; i<5; i++){
try{
Thread.sleep(1000);
Log.d(TAG,"waiting "+ i +" seconds");
}catch(Exception e){}
}
//액티비티를 띄우기 위한 인텐트 객체 생성
Intent showintent = new Intent (getApplicationContext(), MainActivity.class);
//인텐트에 플래그 추가
showintent.addFlags(
intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
showintent.putExtra("command","show");
showintent.putExtra("name",name+"from service");
startActivity(showintent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() 호출됨");
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
앱실행