gpt4 book ai didi

java - 获得多功能服务的最佳方式?

转载 作者:行者123 更新时间:2023-11-30 11:16:40 24 4
gpt4 key购买 nike

好的,开始了...我是 android 编程的新手,迫切需要指导。

我的最终想法是能够向我的服务发送请求,并根据请求的内容执行不同的操作。

示例 1:用户在 Activity 中按下刷新按钮,该按钮会下载信息并显示出来。

示例 2: 用户导航到 Activity 中的登录 fragment ,他可以在其中输入用户名和密码。预先显示他当前保存的信息。

示例3:用户按下小部件,小部件下载信息,然后在小部件中显示一些信息。

希望我已经明白我的想法;将消费任务发送到服务,能够更新当前正在处理的任何显示。服务的 任务取决于对它的要求(服务:我要下载吗?我要获取登录信息吗?我要获取一些其他信息吗?),必须知道如何进行,一旦开始......这引出了我的问题:

我如何告诉我的服务在调用后执行哪个任务?此外,但不太重要的是,更新 View (小部件、 Activity )的最佳、代码效率最高的方法是什么?

背景信息:

  • 我决定使用一项服务来促进小部件和 Activity 。
  • 该服务执行要求很高的任务(下载、数据库在 AsyncTask 上获取/保存等)。
  • 我按如下方式调用我的服务:Intent intent = new Intent(getActivity(), WorkerService.class);
    getActivity().startService(intent);

最佳答案

您可以使用 BoundService

A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.

您有两种创建 BoundService 的方法:

1) 使用 Binder - 这可能是您想要做的。

If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to directly access public methods available in either the Binder implementation or even the Service. This is the preferred technique when your service is merely a background worker for your own application. The only reason you would not create your interface this way is because your service is used by other applications or across separate processes.

2) 使用聊天工具

请记住,该服务在 UI(主)线程中运行。如果您执行持久的操作,您应该创建一个后台线程。

public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();

/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}

关于java - 获得多功能服务的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24758584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com