Android:另一个Activity中的stopService

时间:2012-03-12 10:19:27

标签: java android service android-intent

如何在其他活动中停止我的服务?

我在summaryActivity中启动服务

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

从我的summaryActivity

开始我的statusActivity
Intent intent = new Intent(SummaryActivity.this,
                StatusActivity.class);
intent.putExtra("MessageParcelable", mp);
startActivity(intent);

我的问题是我不知道如何将我的Statusactivity提供给SocketServiceIntent。

5 个答案:

答案 0 :(得分:7)

您应该致电Activity(ContextWrapper)#stopService

stopService(new Intent(SummaryActivity.this, SocketService.class));

答案 1 :(得分:3)

您还没有解释您当前是如何尝试使用stopService()以及您获得的错误。稍微扩展您的问题,您可能会得到更多有用的回复。

您需要从您的活动中调用此内容:

stopService(new Intent(SummaryActivity.this, SocketService.class));

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

在尝试停止之前,请确保所有绑定活动中的未绑定服务。正如Android docs解释的那样,您无法阻止当前绑定到活动的服务。

作为设计提示:通常最好从正在运行的服务中调用stopSelf(),而不是直接使用stopService()。您可以在AIDL界面中添加shutdown()方法,该方法允许活动请求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;
    }

}

这是特别相关的,因为您的Intent名称暗示您可能正在处理网络套接字。您需要确保在服务停止之前正确关闭了套接字连接。

答案 2 :(得分: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))

答案 3 :(得分:0)

只需在summaryActivity中调用stopService

答案 4 :(得分:0)

只需调用stopService()方法

Intent intent = new Intent(this,SocketService.class);
stopService(intent);
相关问题