2011-03-09 7 views
6

메인 액티비티에서 호출 된 서비스를 생성하고 간단한 변수를 전달하여 서비스 내부에서 화면에 액세스하고 토스트합니다. 서비스 내부에서 변수에 액세스하는 올바른 코드를 찾을 수없는 것 같습니다. 어떤 도움이라도 대단히 감사하겠습니다. 감사. 버튼 클릭 리스너 내부에서 서비스를 호출안드로이드 : 서비스에 전달 된 액세스 변수

주요 활동 :

@Override 
public void onClick(View v) { 

    Intent eSendIntent = new Intent(getApplicationContext(), eSendService.class); 

    eSendIntent.putExtra("extraData", "somedata"); 

    startService(eSendIntent); 

} 

eSendService 서비스 클래스 코드 :

public class eSendService extends Service { 


    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     super.onCreate(); 

      // This is the code that I am struggling with. Not sure how to access the 
      // variable that was set in the intent. Please advise. 
      // The below code gives the following error in eclipse: 
      //  The method getIntent() is undefined for the type eSendService 
      Bundle extras = getIntent().getExtras(); 

    } 

} 

다시 도움을 모든 모든 주셔서 감사합니다. 나는이 일을하는 방법을 보여주는 간단한 예제를 찾을 수없는 것 같습니다. 감사.

답변

3

원래 코드가 제공 한 문제점은 무엇입니까? super.onCreate()를 호출하기 전에 데이터를 가져 오려고했는데 문제 일 수 있습니다.

확인
@Override 
public void onCreate() { 
    super.onCreate(); 

    Bundle extras = getIntent().getExtras(); 
    string extraData = extras.getString("extraData"); 

} 
+0

안녕하세요. 나는 변화없이 super.onCreate() 메소드 다음에 그것을 시도했다. 이클립스는 "getIntent()"에 밑줄을 긋고 마우스를 올려 놓으면 "getIntent() 메소드가 eSendService 유형에 대해 정의되지 않았습니다."라는 오류가 발생합니다. 당신의 도움을 주셔서 감사합니다. – RayJamesFun

11

가, 마침내 내 자신의 대답을 발견하고 다른 사람을 돕기 위해 공유하려는 :

난 당신이 원하는 생각합니다.

답변 : onStart() 또는 onStartCommand() (대상 API에 따라 다름)는 activity가 startService()를 호출 한 후 int가 전달되고 호출되는 대상입니다. 나는 그 의도가 onCreate() 메소드에 전달되었다고 생각했지만 실제로는 서비스의 시작 커맨드로 전달됩니다.

@Override public void onStart(Intent intent, int startId) { 
    // TODO Auto-generated method stub 
    super.onStart(intent, startId); 
    String extras; extras = intent.getExtras().getString("extraData"); 
    Toast.makeText(this, extras, Toast.LENGTH_LONG).show(); 
} 
관련 문제