검색결과 리스트
Android 데몬에 해당되는 글 1건
- 2012.03.12 [Android] Demon
글
데몬, 보이지 않는 곳에서 작업을 하는 프로세스이다. 이는 안드로이드의 서비스 컴포넌트 내에 해당하는 것이다.
이는 onCreate에 의해 생성이 되고 onStartCommnd에 의해 실행, onDestory에 의해 생명 주기가 완료된다.
다음은 그 예제이다.
public class ImageViewActivity 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;
}
public IBinder onBind(Intent intent) {
return null;
}
class NewsThread extends Thread {
ImageViewActivity mParent;
Handler mHandler;
String[] arNews = { "1", "2", "3", "4" };
public NewsThread(ImageViewActivity 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 handleMessage(Message msg) {
if (msg.what == 0) {
String news = (String)msg.obj;
Toast.makeText(ImageViewActivity.this, news, 0).show();
}
}
};
}
여기서 하나 더 추가 할 것이 매니페스트에 존대한다. service 부분이다.
<service android:name=".check">
<intent-filter>
<action android:name=".demon" />
</intent-filter>
</service>
위와 같이 꼭 서비스를 등록하고 사용 할 경우에는 Intent를 생성 할 경우 인자 값으로 해당하는 Intent의 이름을 넣어주고 하면 된다.
아래 코드는 그것과 달리 Intent에서 해당 클래스를 바로 불러와서 실행하는 코드이다.
public class ImageViewActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btnstart = (Button)findViewById(R.id.start);
btnstart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(NewsController.this, NewsService.class);
startService(intent);
}
});
Button btnend = (Button)findViewById(R.id.end);
btnend.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(NewsController.this, NewsService.class);
stopService(intent);
}
});
}
}
위에서 보면 이들 서비스는 startService와 stopService에 의해 작동 됨을 확인 할 수가 있다.
RECENT COMMENT