Android:在另一个活动中停止服务

7
如何在另一个Activity中停止我的Service?
我在summaryActivity中启动了这个Service。
SocketServiceIntent = new Intent(this, SocketService.class);
SocketServiceIntent.putExtra("MessageParcelable", mp);
startService(SocketServiceIntent);

从我的概述Activity启动我的状态Activity。
Intent intent = new Intent(SummaryActivity.this,
                StatusActivity.class);
intent.putExtra("MessageParcelable", mp);
startActivity(intent);

我的问题是我不知道如何将SocketServiceIntent分配给我的Statusactivity。


可能是https://dev59.com/0nA75IYBdhLWcg3wrbG_的重复问题。 - seanhodges
谢谢,我在这里找到了一个服务框架的解决方案:https://dev59.com/NlvUa4cB1Zd3GeqPs14h - user1263776
5个回答

9

它在我的StatusActivity中无法工作,因为在范围内没有可访问的SummaryActivity类型的封闭实例。 - user1263776
و‰€ن»¥ه°†ه…¶و›´و”¹ن¸؛StatusActivityم€‚è؟™هڈھوک¯ن¸€ن¸ھن¾‹ه­گم€‚ - MByD
我尝试过了,但它不起作用。我需要使用启动服务时使用的相同 Intent 对象。我不能创建一个新的。我还尝试将 Intent 放入我的 Parcelable 类中。但那也不起作用。 - user1263776
我知道我必须使用stopService方法。 - user1263776

5
您没有说明您目前如何尝试使用stopService()以及出现了什么错误。请详细说明您的问题,这样可能会得到更有帮助的回答。
您需要从您的活动中调用此函数:
stopService(new Intent(SummaryActivity.this, SocketService.class));

将“SummaryActivity”替换为您要停止服务的Activity类的名称。

在尝试停止服务之前,请确保已从所有绑定活动中取消绑定该服务。正如Android文档所解释的那样,您不能停止当前已绑定到 activity 的服务。

设计提示:通常最好从正在运行的服务内部调用stopSelf(),而不是直接使用stopService()。您可以将一个shutdown()方法添加到您的AIDL接口中,允许一个Activity请求调用stopSelf()。这样封装停止逻辑并使您有机会在停止时控制您的服务的状态,类似于处理Thread的方式。

例如:

public MyService extends IntentService {

    private boolean shutdown = false;

    public void doSomeLengthyTask() {
        // This can finish, and the Service will not shutdown before 
        // getResult() is called...
        ...
    }

    public Result getResult() {
        Result result = processResult();

        // We only stop the service when we're ready
        if (shutdown) {
            stopSelf();
        }

        return result;
    }

    // This method is exposed via the AIDL interface
    public void shutdown() {
        shutdown = true;
    }

}

这尤其与你的意图名称相关,因为它表明你可能正在处理网络套接字。在停止服务之前,您需要确保已正确关闭套接字连接。


2

启动服务:

// Java
Intent SocketServiceIntent = new Intent(this, SocketService.class);
SocketServiceIntent.putExtra("MessageParcelable", mp);
startService(SocketServiceIntent);

//Kotlin
startService(Intent(this, SocketService::class.java))

在任何活动中停止服务:

//Java
stopService(new Intent(this, SocketService.class))

//Kotlin
stopService(Intent(this, SocketService::class.java))

0

只需调用stopService()方法

Intent intent = new Intent(this,SocketService.class);
stopService(intent);

0

只需在summaryActivity中调用stopService函数即可


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接