java - 从 MainActivity 调用位于 Service 中的函数
问题描述
所以我有这个服务,一切正常,我唯一想知道的是是否有另一种方法可以getWord(String w)
从服务中调用我的函数。
我有一个用户文本input
,这个输入被发送到getWord(String w)
运行的服务。
ListActivity.java -(这是我的 MainActivity)
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Saving user's input in search field
input = String.valueOf(editSearch.getText());
//Checking if input is valid (not empty and only alphabet characters)
if (!input.equals("") && (input.matches("[a-zA-Z]+"))) {
//Sending input to request
Intent serviceIntent = new Intent(ListActivity.this,WordLeanerService.class);
serviceIntent.putExtra("SearchForWord", input);
startService(serviceIntent);
} else {
Toast.makeText(getApplicationContext(), getString(R.string.input_invalid_message_toast), Toast.LENGTH_LONG).show();
}
}
});
在服务(WordLeanerService.java)中,我执行以下操作
public int onStartCommand(final Intent intent, int flags, int startId) {
String Checker;
if ((Checker = intent.getStringExtra("SearchForWord")) != null ) {
getWord(Checker); //this activates the service function
}
return START_NOT_STICKY;
}
我之所以问,是因为我认为每次需要运行此功能时都启动服务有点愚蠢?我可以使用我在ListActivity
(MainActivity) 中进行的绑定吗?
我的 onCreate() --> ListActivity 中也有这些(注意:按钮也在 OnCreate 中。)我可以用它来做些什么吗?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(ListActivity.this,WordLeanerService.class).putExtra("inputExtra", s1));
setupConnectionToWLservice();
}
private void setupConnectionToWLservice(){
WLConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bindService(new Intent(ListActivity.this,WordLeanerService.class),WLConn, Context.BIND_AUTO_CREATE);
//ref: http://developer.android.com/reference/android/app/Service.html
WLService = ((WordLeanerService.ServiceBinder)service).getService();
//TODO: probably a good place to update UI after data loading
}
public void onServiceDisconnected(ComponentName className) {
//ref: http://developer.android.com/reference/android/app/Service.html
WLService = null;
}
};
}
所以我的问题是:我可以用另一种方式调用该getWord(String w)
函数,所以我不必StartService
每次需要运行它时都调用它吗?
解决方案
推荐阅读
- media-queries - 如何使用 Shopify 为平板电脑/Ipad 启用汉堡菜单 | 出道主题2020
- ios - 我可以检测用户是否通过 iOS 14 中的主页按钮或锁定按钮离开?
- php - 如何创建在其他页面上调用 jQuery 函数的复选框事件?
- python - 我不断收到一条错误消息,上面写着“pygame.error:无法打开racecar.png”
- sql - 如何修复重复元组中的错误并正确排序?
- lisp - `uiop/package:define-package`和`defpackage`之间的区别?
- android - 将 ViewModel 中的空值返回到回收器视图列表的存储库类
- c++ - C++ 未命名类型结构成员
- node.js - 如何将项目添加到猫鼬数组
- python - 从图片中删除特定的彩色线条