Android通过活动控制服务

时间:2013-04-12 11:00:25

标签: android service

对于聊天应用程序,我需要管理用户和Web服务之间通信的服务。我决定使用通常的Android服务组件。

我现在如何启动服务,我也知道如何从服务向活动发送消息,但我如何从活动中控制服务? 例如。用户发送消息,因此我必须使服务发送,例如包含消息的http请求。或者用户想要结束聊天会话,因此活动必须使服务发送包含结束聊天会话的命令的请求。

1 个答案:

答案 0 :(得分:0)

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

在AIDL中,您可以在服务中实现方法,并通过活页夹调用这些方法。

所以在你的情况下,1)在服务中实现sendMessage(String msg)

2)在aidl文件中声明此方法并从服务

调用
mService.sendMessage(msg);

不使用AIDL编辑:

服务类

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);
    }

}

活动类

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();
        }
    }
}