2016-07-18 6 views
-1

Android에서 IntentService와 Service의 차이점을 파악하기 위해 아래에 게시 된 Service 클래스의 작은 테스트를 작성했습니다. MainActivity에는 Button이 있는데, 눌려지면 서비스는 아래 코드와 같이 startService()를 사용하여 시작되며 onStartCommand()가 호출됩니다. onStartCommand()에서 10 초 동안 루프를 실행하고 그 루프가 UI "the butoon"을 차단할 것이라고 예상했던 을 예상했습니다. 실제로 처음 서비스를 시작했을 때 정확히 무슨 일이 발생했는지를 10 초 후에 이 경과하면 버튼을 누르면 onStartCommand()가 호출되지만 onStartCommand() 내부의 로그 메시지는 결코 표시되지 않습니다. UI가 차단되지 않습니다.onStartCommand() 본문이 한 번만 실행되는 이유는 무엇입니까?

누구나 onStartCommand()의 본문이 어떻게 실행되는지 설명하고 서비스가 처음 시작되었을 때만 UI를 차단할 수 있습니까?

MainActivity

public class MainActivity extends AppCompatActivity { 

private Button mbtnSend = null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    this.mbtnSend = (Button) findViewById(R.id.btn_send); 
    this.mbtnSend.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(getApplicationContext(), MyService.class); 
      startService(intent); 
     } 
    }); 
} 
} 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    registerReceiver(this.mBCR_VALUE_SENT, new IntentFilter(MyIntentService.INTENT_ACTION)); 

    this.mbtnSend = (Button) findViewById(R.id.btn_send); 
    this.mbtnSend.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(getApplicationContext(), MyIntentService.class); 
      intent.putExtra("intent_key", ++i); 
      startService(intent); 
     } 
    }); 
} 

}

MyIntentService :

public class MyService extends Service{ 
private final String TAG = this.getClass().getSimpleName(); 
private long mStartTime; 

@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.w(TAG, SubTag.msg("onCreate")); 

    this.mStartTime = TimeUtils.getTSSec(); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.w(TAG, SubTag.msg("onStartCommand")); 

    while ((TimeUtils.getTSSec() - this.mStartTime) <=10) { 
     Log.w(TAG, SubTag.msg("time: " + (TimeUtils.getTSSec() - this.mStartTime))); 
     SystemClock.sleep(1000); 
    } 

    return Service.START_STICKY; 
} 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    Log.w(TAG, SubTag.msg("onBind")); 

    return null; 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    Log.w(TAG, SubTag.msg("onDestroy")); 
} 

}

답변

1

당신은 mStartTime 01으로 설정하는 onCreate()에이 있습니다. 즉, 초기화는 한 번만 수행됩니다.

이후에 mStartTime 타임 스탬프가 업데이트되지 않으므로 while 루프가 실행되지 않습니다.

mStartTime을 초기화하는 줄을 while 루프 전에 onStartCommand()으로 이동하면 스레드가 다시 멈추게됩니다.

+0

오 .. 예 .. 진정한 .. 감사합니다. .. coulndt는 그것을 깨닫습니다. – user2121

관련 문제