サービス概要3

2339 ワード

サービスとactivityは同じスレッドにあります.
直接コード:
public class MyServiceActivity extends Activity {
	protected static final String TAG = "MyServiceActivity";
	private Button btnStartNormalService;
	private Button btnStartIntentService;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartNormalService=(Button)findViewById(R.id.btnStartNormalService);
        btnStartIntentService=(Button)findViewById(R.id.btnStartIntentService);
        btnStartIntentService.setOnClickListener(listener);
        btnStartNormalService.setOnClickListener(listener);   
    }
	private OnClickListener listener=new OnClickListener()
	{		
		@Override
		public void onClick(View v)
		{
			Intent intent;
			switch (v.getId())
			{
			case R.id.btnStartNormalService:
				intent=new Intent(MyServiceActivity.this, mService.class);
				Log.i(TAG, " ID:"+Thread.currentThread().getId());
				startService(intent);
				break;
			case R.id.btnStartIntentService:
//				intent=new Intent(IntentActivity.this, ExampleIntentService.class);
//				Log.i(TAG, " ID:"+Thread.currentThread().getId());
//				startService(intent);
				break;
			default:
				break;
			}		
		}
	};
}
 public class mService extends Service {
	private static final String TAG = "MyServiceActivity";
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG,"Myservices Id"+Thread.currentThread().getId());
		return START_STICKY; // 
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}

AndroidManifest.xmlファイルでserviceを構成するには:
    
 
最終logは結果的にスレッドidですべて1で、等しいです