首页 > 解决方案 > 从 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每次需要运行它时都调用它吗?

标签: javaandroid

解决方案


推荐阅读