我需要访问一个简单的整数变量,它保存着editText元素的值。这个值作为一个公共字段存储在我的Activity类中。在我的服务中,我创建了一个来自我的Activity类的对象:
CheckActivity check = new CheckActivity();
我正在尝试通过以下方式访问它:
check.getFirstPosition();
但它返回零。如何将值从Activity传递给Service?
我需要访问一个简单的整数变量,它保存着editText元素的值。这个值作为一个公共字段存储在我的Activity类中。在我的服务中,我创建了一个来自我的Activity类的对象:
CheckActivity check = new CheckActivity();
我正在尝试通过以下方式访问它:
check.getFirstPosition();
在Android中,无论是Activity
还是Service
,你需要使用意图(Intent)来在不同的组件之间传递数据。
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
了。CheckActivity check = new CheckActivity()
时,会创建一个新的CheckActivity
实例,并且毫无疑问它将返回零。此外,在Android中,您永远不应尝试像这样创建活动对象。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);
unregisterReceiver(broadcastReceiver);
Intent
来创建一个Activity。Intent
使用context.startService()
方法传递值,或者绑定它并通过引用传递值。BroadcastReceiver
或 Handler
。