如何将活动中的价值传递给Android中的服务? [英] How to pass value from Activity to a Service in Android?

查看:74
本文介绍了如何将活动中的价值传递给Android中的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need access a simple int variable which holds an editText element value. The value is stored as a public field on my Activity class. On my Service, I created an object from my activity class:

CheckActivity check = new CheckActivity();

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

and I am trying to access it by:

check.getFirstPosition();

,但它返回零.我应该怎么做才能将值从活动传递给服务?

but it returns zero. What should I do to pass the value from an Activity to a Service?

推荐答案

您不能从服务中创建类似的对象.我认为您是Java的新手.当您执行CheckActivity check = new CheckActivity()时,将创建您的CheckActivity的新实例,毫无疑问它将返回零.另外,您永远不要尝试在android中创建此类活动的对象.

You cannot create an object like that from your service. I think you are new to Java. When you do CheckActivity check = new CheckActivity() a new instance of your CheckActivity is created and no doubt it will return zero. Also you should never try creating objects of activities like this in android.

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

As far as your question is concerned you can pass your editText value to your service via a broadcast receiver.

看看.

如果在创建服务之前具有editText值,则可以简单地将其作为

Also if you have the editText value before creating the service you can simply pass it as intent extra , else you can use the broadcast approach.

为您服务

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

在您的活动中

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

还可以在活动的onCreate中声明您的接收者,并在onDestroy中取消对其的取消注册

Also declare your receiver in onCreate of activity and unregeister it in onDestroy

unregisterReceiver(broadcastReceiver);

这篇关于如何将活动中的价值传递给Android中的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆