【问题标题】:Android: stopService in another ActivityAndroid:在另一个活动中停止服务
【发布时间】:2012-03-28 17:53:33
【问题描述】:

如何在另一个 Activity 中停止我的服务?

我在我的 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。

【问题讨论】:

标签: java android service android-intent


【解决方案1】:

你应该打电话给Activity(ContextWrapper)#stopService:

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

【讨论】:

  • 它在我的 StatusActivity 中不起作用,因为“范围内没有 SummaryActivity 类型的封闭实例可访问”。
  • 所以把它改成StatusActivity。这只是一个例子。
  • 我做了,但它不起作用。我需要与启动服务相同的意图对象。我不能做一个新的。我还尝试将 Intent 放在我的 Parcelable 类中。但这也行不通。
  • 我知道我必须使用stopService方法。
【解决方案2】:

您尚未解释您当前如何尝试使用 stopService() 以及您遇到了什么错误。稍微扩展您的问题,您可能会得到更多有用的回答。

你需要从你的活动中调用它:

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

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

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

作为设计提示:从正在运行的服务中调用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;
    }

}

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

【讨论】:

    【解决方案3】:

    启动服务:

    // 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))
    

    【讨论】:

      【解决方案4】:

      只需在summaryActivity中调用stopService

      【讨论】:

        【解决方案5】:

        只需调用stopService() 方法

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多