android中activity向service中傳值


和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)傳值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM