Android 服务和活动

Android 服务和活动,android,service,binding,android-activity,Android,Service,Binding,Android Activity,我有一个service GPS.java和一个activity message.java,它绑定到所提到的服务(GPS.java)。我使用活页夹和服务连接将它们绑定。我想要使用putExtra(Sring,value)发送的活动类的值。我将如何在我的服务中接收它们?如果您在启动/绑定到服务时提供了intent中的值,您可以从中访问数据 但是,如果您使用的是活页夹,则需要创建一种方法来提供服务值,因为在onBind中接收到的意图不会包含任何额外内容 以下是一个例子: 在职期间: private f

我有一个service GPS.java和一个activity message.java,它绑定到所提到的服务(GPS.java)。我使用活页夹和服务连接将它们绑定。我想要使用putExtra(Sring,value)发送的活动类的值。我将如何在我的服务中接收它们?

如果您在启动/绑定到服务时提供了intent中的值,您可以从中访问数据

但是,如果您使用的是活页夹,则需要创建一种方法来提供服务值,因为在
onBind
中接收到的意图不会包含任何额外内容

以下是一个例子:

在职期间:

private final ExampleBinder binder = new ExampleBinder();

private class ExampleBinder extends Binder {
    public void setExtras(Bundle b) {
        // Set extras and process them
    }

    public ExampleService getService() {
        return ExampleService.this;
    }

    public void registerClient(ClientInterface client) {
        synchronized(clients) {
            clients.add(client);
        }
    }

    public void unregisterClient(ClientInterface client) {
        synchronized(clients) {
            clients.remove(client);
        }
    }
};

public IBinder onBind(Intent intent) {
    return binder;
}

private final HashSet<ClientInterface> clients = new HashSet<ClientInterface>();

public static interface ClientInterface {
    int value1();
    String value2();
}
我可以补充一点,这都是假设您没有使用AIDL,如果您认为解决方案非常类似,只需在接口声明中添加一个额外的方法

您应该在此处阅读有关绑定服务的更多信息: 或者看一个例子:


SDK中还包括一个名为LocationService.java的示例。我认为您必须提供一些示例代码,说明您所拥有的功能。getExtras只能用于onStart()…但我使用的是bindService()。您需要在活页夹中创建方法,以便在绑定到服务后设置数据。是否从我的服务中的“活动”中读取值?是否有任何方法可以直接使用R.java文件读取活动中的这些值?或不请告诉我相关代码这样做使用活页夹?
public class ExampleActivity extends Activity implements ExampleService.ClientInterface {
    private final ServiceConnection connection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            // Handle unexpected disconnects (crashes)
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            ExampleService.ExampleBinder binder = (ExampleService.ExampleBinder) service;
            binder.registerClient(ExampleActivity.this);
        }
    };

public void onResume() {
    bindService(new Intent(this, ExampleService.class), connection, Context.BIND_AUTO_CREATE);
}

public void onPause() {
    unbindService(connection);
}

public int value1() {
    return 4711;
}

public String value2() {
    return "foobar";
}