Notice
Recent Posts
Recent Comments
Link
관리 메뉴

설.현.아빠

[개발 Tip] 서비스 사용예제 (음악재생) 본문

안드로이드/Service

[개발 Tip] 서비스 사용예제 (음악재생)

설.현.아빠 2011. 2. 11. 11:06




package com.example;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

// http://marakana.com/forums/android/examples/60.html
public class MyService extends Service {
  private static final String TAG = "MyService";
  MediaPlayer player;

  
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
  
  @Override
  public void onCreate() {
    Log.d(TAG, "onCreate");
    Toast.makeText(this"My Service Created", Toast.LENGTH_LONG).show();
        
    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
  }

  @Override
  public void onDestroy() {
    Log.d(TAG, "onDestroy");
    Toast.makeText(this"My Service Stopped", Toast.LENGTH_LONG).show();
    
    player.stop();
  }
  
  
  @Override
  public void onStart(Intent intent, int startid) {
    Log.d(TAG, "onStart");
    handleCommand(intent);
  }
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
      handleCommand(intent);
      // We want this service to continue running until it is explicitly
      // stopped, so return sticky.
      return START_STICKY;
  }
  
  private void handleCommand(Intent intent) {
    Toast.makeText(this"My Service Started", Toast.LENGTH_LONG).show();    
    player.start();
  }
  
}


서비스 실행시
onCreate --> onStartCommand가 호출되는것을 확인할수가 있습니다. 시스템에 의해서 종료된후 다시 실행되는 경우 onCreate --> onStartCommand순으로 호출된다. 단, 시스템에 의해서 재 실행된 경우 onStartCommand에는 인자(intent)가 null 값이 들어온다.

'안드로이드 > Service' 카테고리의 다른 글

안드로이드에서 Romote Service 구현하기  (0) 2011.02.11
Comments