제가 아래있는 데로 다 따라했는데요 ..
왜 버튼누르면 아무런반응이 없는걸까요? ㅠㅠㅠ
--------------------------------------------------------------------
- 백그라운드 데몬 : 백그라운드에서 계속 실행되는 프로세스이다.
- 원격 호출 인터페이스 : 자신의 기능을 메소드로 노출시키며 클라이언트는 메소드를 호출함으로써 서비스를 이용한다. COM, CORBA에 대응하는 개념이다.
데몬일때는 백그라운드 서비스를 시작하라는 onStartCommand 메소드가 호출되고 원격호출일 경우에는 클라이언트에게 인터페이스를 노출하는 onBind 메소드가 호출된다.
NewsService.java |
package test.NewsService;
import android.app.*; import android.content.*; import android.os.*; import android.widget.*;
public class NewsService extends Service { boolean mQuit; public void onCreate() { super.onCreate(); } public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service End", 0).show(); mQuit = true; } public int onStartCommand (Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); mQuit = false; NewsThread thread = new NewsThread(this, mHandler); thread.start(); return START_STICKY; } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } class NewsThread extends Thread { NewsService mParent; Handler mHandler; String[] arNews = { "일본, 독도는 한국땅으로 인정", "번데기 맛 쵸코파이 출시" }; public NewsThread(NewsService parent, Handler handler) { mParent = parent; mHandler = handler; } public void run() { for (int idx = 0 ; mQuit == false ; idx++) { Message msg = new Message(); msg.what = 0; msg.obj = arNews[idx % arNews.length]; mHandler.sendMessage(msg); try { Thread.sleep(5000); } catch (Exception e) { ; } } } } Handler mHandler = new Handler() { public void handlerMessage(Message msg) { if(msg.what == 0) { String news = (String)msg.obj; Toast.makeText(NewsService.this, news, 0).show(); } } }; }
|
위 서비스를 실행시키면 onStartCommand 메소드가 실행이 되며 비동기로 스레드가 실행되게 된다. 실행된 스레드는 부모 핸들러에게 메시지를 보내면 부모 스레드는 Toast메시지로 해당 메시지를 보여주게 된다.
위 서비스를 실행하게 될 Activity를 작성해 보자.
NewsContoller.java |
public class NewsContoller extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = new Intent(NewsContoller.this, NewsService.class); startService(intent); } } |
서비스도 응용프로그램을 구성하는 컴포넌트이므로 Manifest파일에 등록해주어야 한다.
<service android:name=".NewsService" android:enabled="true">
<intent-filter>
<action android:name="test.News" />
</intent-filter>
</service>
아래는 서비스를 실행, 종료시키는 메소드 이다.
ComponentName startService (Intent service)
boolean stopService (Intent service)