【问题标题】:How to close a service from an activity?如何从活动中关闭服务?
【发布时间】:2023-04-03 01:51:01
【问题描述】:

我正在尝试制作一个只有一个活动的应用程序,当您按下按钮时,应用程序将关闭,但服务仍保留在后台。但是,我想要一个名为“关闭应用程序”的选项按钮(在 onCreateOptionsMenu 中),因此当您单击它时,Activity 为finish(); 并且服务被终止。问题是我知道如何关闭 Activity,但不知道如何从 Activity 中终止服务。这是我的代码的一部分(为简单起见,我省略了几个基本方法):

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bDone.setOnClickListener(this);
}

public void Onclick(){
        Intent serv = new Intent(Main.this, Bground.class);
        startService(serv);

        finish();
}


public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.closeApp) {
            finish();
        }
        return super.onOptionsItemSelected(item);
}

我尝试将Intent serv; 作为一个全局变量并在 onOptionsItemSecected 中将stopService(serv); 写在finish(); 的正上方,但它给了我一个错误。

谢谢!

【问题讨论】:

  • 什么样的错误?发布堆栈跟踪。

标签: android android-activity service


【解决方案1】:

在您的 onStop() 中尝试 unbindService()

【讨论】:

  • 使用 'serv' 作为参数或不使用参数:“ContextWrapper 类型中的方法 unbindService(ServiceConnection) 不适用于参数 (Intent)”。
【解决方案2】:

我终于这样解决了

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.closeApp) {
        stopService(new Intent(Main.this, Bground.class));
        finish();
    }

只需添加stopService(new Intent(Main.this, Bground.class));

感谢这个帖子:How to call stopservice() method of Service class from the calling activity class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多