和activity中互相傳值類似
在activity中
Intent regIntent = new Intent(this, ChatService.class);
regIntent.putExtra("student_id", student_id);
startService(regIntent);
然后再service中的onStart函數中獲取該值
student_id=intent.getStringExtra("student_id");
System.out.println("sevice_student_id---------------"+student_id);
當然寫到這里還是不能傳的,不然會報錯!!!
我們需要在Mainfeist文件中注冊這個service
銷毀Service寫在activity的onDestroy方法里:
@Override
protected void onDestroy() {
ChatActivity.this.stopService(new
Intent(ChatActivity.this,
ChatService.class));
super.onDestroy();
}
補充:
也可以從public int onStartCommand(Intent intent, int flags, int startId)中取出從activity中傳過來的值。intent.getExtra()獲得bundle對象,可從中取值。
也可以用bindService(intent, conn,BIND_AUTO_CREATE);傳值,把要傳的值綁定在intent里,在service的public IBinder onBind(Intent intent) 方法里取得intent。
可以在service里面注冊一個廣播,在activity里sendbroadcast(intent)傳值。
