我知道本地服务在主进程的UI线程中运行,与活动相同。 根据这个原则,当我在活动中做某事时,如果在服务中运行耗费时间,它不应该立即起作用。
但下面的例子并非如此。 谁能告诉我实情? 非常感谢!
package com.example.testservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "LocalService";
private MyService.LocalBinder binder = new MyService.LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
Log.i(TAG, "onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
//I do something time-consuming in here.
for (int i = 1; i <= 10; i++) {
Log.i(TAG, "Name:" + Thread.currentThread().getName()
+ ".Service i:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind!");
return super.onUnbind(intent);
}
}
以下是活动代码:
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btnTimeConsuming:
for(int i = 1;i <= 10; i ++)
{
Log.i(TAG, "Name:" + Thread.currentThread().getName() + ".Activity i:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
break;
case R.id.btnStartService:
startService(intent);
break;
default:
break;
}
}
当我点击按钮“R.id.btnStartService”时,我点击按钮“R.id.btnTimeConsuming” 它打印下面的日志。
服务中的任务和服务中的任务变得复杂。为什么呢?