要了解Android中IntentService和Service之間的區別,我創建了以下發布的Service類的小測試。在MainActivity具有一個按鈕,當被按下時,所述 服務將使用startService()作爲在代碼如下所示開始,這將導致對onStartCommand()的調用。在onStartCommand()中,我運行一個循環10秒,並且我期望,該循環將阻止UI「the butoon」。其實發生了什麼事情什麼時候我第一次啓動該服務,但是當我在10秒 經過後按下按鈕,它會導致對onStartCommand(通話),但onStartCommand(裏面的日誌消息)永遠不會顯示加UI永遠不會被阻止。爲什麼onStartCommand()的主體只能執行一次?
任何人都可以請解釋執行onStartCommand()的主體,只有在服務第一次啓動時纔會阻止用戶界面,並且永遠不會?
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"));
}
}
哦..yes..ur true..thanks..i coulndt意識到, – user2121