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

How to pass value from Activity to a Service in Android?

我需要访问一个保存 editText 元素值的简单 int 变量。该值作为 public 字段存储在我的 Activity class 中。在我的服务中,我从 activity class:

创建了一个对象
CheckActivity check = new CheckActivity();

我正在尝试通过以下方式访问它:

check.getFirstPosition();

但它 returns 为零。我应该怎么做才能将值从 Activity 传递给服务?

CheckActivity check = new CheckActivity();

永远不要这样做。使用 Intent 来创建一个 activity。

What should I do to pass the value from an Activity to a Service?

您可以使用 context.startService() 方法通过 Intent 传递它。或者,您可以绑定到它并通过引用传递一个值。

您也可以考虑使用 BroadcastReceiverHandler

您需要使用意图在不同 Android 组件之间传递数据,无论是 Activity 还是 Service

Intent intent = new Intent(this, YourService.class);
intent.putExtra("your_key_here", <your_value_here>); 

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

startService(intent);

现在您可以使用 onBind()onStartCommand()(取决于您使用服务的方式)来使用作为参数传递的 intent

String editTextValue = intent.getStringExtra("your_key_here");

您现在可以在任何地方使用 editTextValue

您不能从您的服务中创建这样的对象。我认为您是 Java 的新手。当您执行 CheckActivity check = new CheckActivity() 时,您的 CheckActivity 的新实例将被创建,毫无疑问它将 return 归零。此外,您永远不应该尝试在 android.

中创建这样的活动对象

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

看看this

此外,如果您在创建服务之前有 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);

在你的activity

Intent broadcast1 = new Intent("getting_data");
        broadcast.putExtra("value", editext.getText()+"");
        sendBroadcast(broadcast1);

同时在 activity 的 onCreate 中声明你的接收器并在 onDestroy

中注销它
unregisterReceiver(broadcastReceiver);