Android,使用线程启动服务并在完成时警告活动

发布于 2024-12-08 22:43:07 字数 300 浏览 0 评论 0原文

我有一个服务,它有一个从 URL 下载图像并返回 Uri 的方法。 当该服务具有所有预期功能时,它会变得更加复杂。所以, 我在线程中调用它的方法。

我的问题是如何警告活动该服务已完成其工作。

我可以更改类 isFinished 变量,但活动必须不断检查 为了它的价值。

我只想让服务告诉活动它的工作已经完成并且资源已经完成 可供使用。

我认为调用 stopSelf() 的服务中存在某些内容,并且该活动是 通过“onServiceDisconnected”发出警告,但这似乎不太“政治正确”。

提前致谢

I have a service which has a method that downloads an image from an URL and returns an Uri.
That service will get more complex when it has all the intended features. Therefore,
I'm invoking its methods within a thread.

My problem is how to warn the activity that the service has done it's work.

I could change a class isFinished variable but the activity had to be constantly checking
for its value.

I just want the service to tell the activity that it's work is done and the resources are
available for use.

I thought something in the lines of the service calling stopSelf() and the activity was
warned through "onServiceDisconnected" but that didn't seem very "political correct".

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空宴 2024-12-15 22:43:07

有两种方法可以做到这一点。
1. 您可以通过触发意图来启动您的活动。
2. 您可以广播一个意图并在您的应用程序中为其编写接收器,当您的接收器收到意图并在此方法中调用 onreceive 方法时,您可以使用意图启动您的活动。

干杯...

There are two ways to do it.
1. You can start your activity using by firing an intent.
2. You can Broadcast an intent and write receiver for it in your app when your receiver receives intent and onreceive method is called in this method you can start your activity using intent.

cheers...

何止钟意 2024-12-15 22:43:07
public class MyActivity extends Activity{

    public MyActivity() {
        ...
        MyThread thread = new MyThread(this);
        thread.start();
    }

    public void onFinishedThread(...) {

    }
}

class MyThread extends Thread {

    MyActivity activity;

    public MyThread(MyActivity activity) {
        this.activity = activity;
    }

    public void run() {
        // do work
        ...
        this.activity.onFinishedThread(...);
    }
}
public class MyActivity extends Activity{

    public MyActivity() {
        ...
        MyThread thread = new MyThread(this);
        thread.start();
    }

    public void onFinishedThread(...) {

    }
}

class MyThread extends Thread {

    MyActivity activity;

    public MyThread(MyActivity activity) {
        this.activity = activity;
    }

    public void run() {
        // do work
        ...
        this.activity.onFinishedThread(...);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文