2013-04-12 19 views
1

對於聊天應用程序,我需要管理用戶與Web服務之間通信的服務。我決定使用通常的Android服務組件。Android根據活動控制服務

我現在該如何啓動服務,我也知道如何將消息從服​​務發送到活動,但是如何從活動控制服務? 例如用戶發送消息,所以我必須讓服務發送例如包含消息的http請求。或者用戶想要結束聊天會話,因此活動必須使該服務發送包含命令以結束聊天會話的請求。

回答

0

您可以使用AIDL http://developer.android.com/guide/components/aidl.html

在AIDL,可以實現在服務方法,並通過粘合劑調用從活動的方法。

所以你的情況,1)在服務

2)中聲明AIDL文件這種方法實現的sendMessage(絃樂味精),並從服務調用

mService.sendMessage(msg); 

編輯,而無需使用AIDL:

Service類

public class LocalService extends Service { 
    private final IBinder mBinder = new LocalBinder(); 
    private final Random mGenerator = new Random(); 
    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return mBinder; 
    } 

    public class LocalBinder extends Binder{ 
     LocalService getService(){ 
      return LocalService.this; 
     } 
    } 

    public int getRandomNumber() 
    { 
     return mGenerator.nextInt(100); 
    } 

} 

Activity類

public class BindingActivity extends Activity { 
    LocalService mService; 
    boolean mbound = false; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_binding); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_binding, menu); 
     return true; 
    } 

    @Override 
    protected void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 
     Intent intent = new Intent(this, LocalService.class); 
     bindService(intent,mConnection,Context.BIND_AUTO_CREATE); 

    } 

    @Override 
    protected void onStop() { 
     // TODO Auto-generated method stub 
     super.onStop(); 
     if(mbound) 
     { 
      unbindService(mConnection); 
      mbound = false; 
     } 
    } 
    private ServiceConnection mConnection = new ServiceConnection(){ 


     @Override 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      // TODO Auto-generated method stub 
      LocalBinder binder = (LocalBinder)service; 
      mService = binder.getService(); 
      mbound = true; 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName name) { 
      // TODO Auto-generated method stub 
      mbound = false; 

     } 
    }; 

    public void onClick(View view) 
    { 
     if(mbound) 
     { 
      int num = mService.getRandomNumber(); 
      Toast.makeText(this, "number: "+num, Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 
+0

Thx我會檢查這一點,但我用於進程間通信的AIDL和這個服務將運行在與主線程相同的進程。希望有更輕的權重方法 – user1324258

+0

如果它們在同一個進程中運行,那麼不需要使用AIDL,只需通過擴展服務創建服務並實現其方法並調用像mService.sendMessage(msg) – Sunny

+0

這樣的活動即可檢查我的編輯回答,我相信這是你正在尋找的 – Sunny