如何将值从Activity传递到Android中的服务?

Kaa*_*rel 3 android android-service android-activity

我需要访问一个包含editText元素值的简单int变量.该值存储为Activity类的公共字段.在我的服务上,我从我的活动类创建了一个对象:

CheckActivity check = new CheckActivity();
Run Code Online (Sandbox Code Playgroud)

我试图通过以下方式访问它:

check.getFirstPosition();
Run Code Online (Sandbox Code Playgroud)

但它返回零.如何将值从活动传递到服务?

var*_*nkr 7

您无法从您的服务创建类似的对象。我认为您是 Java 新手。当您创建CheckActivity check = new CheckActivity()一个新实例时CheckActivity,毫无疑问它将返回零。另外,你永远不应该尝试在 android 中创建这样的活动对象。

就您的问题而言,您可以通过广播接收器将 editText 值传递给您的服务。

看看这个

此外,如果您在创建服务之前拥有 editText 值,则可以简单地将其作为Intent extra传递,否则您可以使用广播方法。

为您服务

broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equalsIgnoreCase("getting_data")) {
                    intent.getStringExtra("value")
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        // set the custom action
        intentFilter.addAction("getting_data"); //Action is just a string used to identify the receiver as there can be many in your app so it helps deciding which receiver should receive the intent. 
        // register the receiver
        registerReceiver(broadcastReceiver, intentFilter);
Run Code Online (Sandbox Code Playgroud)

在你的活动中

Intent broadcast1 = new Intent("getting_data");
        broadcast.putExtra("value", editext.getText()+"");
        sendBroadcast(broadcast1);
Run Code Online (Sandbox Code Playgroud)

还要在 Activity 的 onCreate 中声明您的接收器,并在 onDestroy 中取消注册它

unregisterReceiver(broadcastReceiver);
Run Code Online (Sandbox Code Playgroud)


Sha*_*ari 5

您需要使用意图不同的Android组件间传递数据的是它Activity还是Service.

Intent intent = new Intent(this, YourService.class);
intent.putExtra("your_key_here", <your_value_here>); 
Run Code Online (Sandbox Code Playgroud)

然后像这样开始你的服务 -

startService(intent);
Run Code Online (Sandbox Code Playgroud)

现在您可以使用onBind()onStartCommand()(取决于您使用服务的方式)将intentpass作为参数使用

String editTextValue = intent.getStringExtra("your_key_here");
Run Code Online (Sandbox Code Playgroud)

您可以editTextValue随时随地使用.