안드로이드 개발 질문/답변
(글 수 45,052)
Activity A 에서 <Start>와 <End> 버튼을 만들고. Start를 누르면
Service B 에서 백그라운드(서비스)가 실행되서 토스트를 발생시켜
Activity에 보여주도록 하는 소스를 만들었사온데
제목과 같이 전혀 반응이 없습니다.
실행중에 죽는 것도 없고,
그렇다고 에러메세지가 나오는 것도 아닌데
왜 토스트는 발생되지 않는지 궁금합니다.
아래에 소스와 메인, 메니페스트 붙여드리오니
(저도 계속 찾고있지만) 확인 부탁드려도 될까요..
답변 기다리고 있습니다. 감사합니다.
// 백그라운드(서비스)
package com.android;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
/*
* 서비스: 백그라운드에서 계속적으로 실행되는 프로세스로 클라이언트가
* 가동시켜 놓으면 사용자의 명령이 없어도 지속적으로 실행
* (mp3 Player ..)
*
* @Life Cycle
* onCreate(): onStart()
* onBind(): 클라이언트가 서비스와 영속적 연결관계를 유지할 경우
* Context.bindService를 호출.
* onDestroy(): 서비스 종료시 호출.
*/
public class BackgroundTestActivity extends Service {
/** Called when the activity is first created. */
private boolean isRunning;
class MyThread extends Thread{
private Handler handler;
private String[] items = {"android", "framwork", "java", "Ajax", "JSP" };
public MyThread(Handler handler){
this.handler = handler;
}
public void run(){
int n = 0;
while(!isRunning){
Message msg = new Message();
msg.what = 0;
msg.obj = items[n];
handler.sendMessage(msg);
try{
sleep(1000);
} catch(Exception e){
}
n++;
if(n>=items.length)
n= 0;
}
}
}
private Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what==0){
String str= (String) msg.obj;
Toast.makeText(BackgroundTestActivity.this, str, Toast.LENGTH_LONG).show();
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void OnDestroy(){
super.onDestroy();
Toast.makeText(BackgroundTestActivity.this, "Service End", Toast.LENGTH_SHORT).show();
isRunning = true;
}
public int onStartCommand(Intent intent, int flags, int startId){
super.onStartCommand(intent, flags, startId);
// 클라이언트가 startService 메소드에 의해 실질적으로 일을 하는 메소드
// 백그라운드에서 실행된다.
isRunning = false;
MyThread th = new MyThread(handler);
th.start();
Log.d("SEHEE","on start Command");
return START_STICKY;
}
}
// 엑티비티
D:\Source\eclipse\workspace\ServiceTest\src\com\android\ServiceTestActivity.java
package com.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class ServiceTestActivity extends Activity {
//@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//서비스 시작
Intent intent = new Intent(ServiceTestActivity.this, BackgroundTestActivity.class);
startService(intent);
}
});
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//서비스 중지
Intent intent = new Intent(ServiceTestActivity.this, BackgroundTestActivity.class);
stopService(intent);
}
});
}
}
// main.xml
D:\Source\eclipse\workspace\ServiceTest\res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/btn1"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text="Start"
/>
<Button
android:id="@+id/btn2"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text="Stop"
/>
</LinearLayout>
// AndroidManifest.xml
D:\Source\eclipse\workspace\ServiceTest\AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:label="@string/app_name"
android:name=".ServiceTestActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Background 등록부 -->
<Service android:name="com.android.BackgroundTestActivity"
android:enabled="true">
<intent-filter>
<action android:name="com.android.INFORMATION"/>
</intent-filter>
</Service>
</application>
</manifest>



답변이 될런지는 정학하지 않지만 몇자 적습니다.
service에서 메인 쪽의 ui 를 변경하는게 안되는것으로 알고 있습니다. 제가 아는 선에서는 이런경우 메인 쓰레드의 ui 를 변경 할수 없다는 에러가 발생을 하는것으로 아는데 에러가 안나신다니 이부분은 정확히 모르겠네요.
해결방법은 handler 를 메인 쪽에 만드시고 서비스쪽에 handler 를 넘겨서 sendMessage 하시고 메인의 handleMessage 에서 toast 를 띄우는 방법으로 하셔야 할것 같습니다.