【问题标题】:Android: Run code when application is permanently closedAndroid:当应用程序永久关闭时运行代码
【发布时间】:2017-08-21 17:52:55
【问题描述】:

所以我有我想在我的应用程序关闭时调用的代码。不仅仅是当它被发送到后台或表面被破坏时。我该怎么做呢?有没有可以在 SurfaceViewActivity 类中覆盖的方法?

新编辑 - 当前BackgroundService 类:

public class BackgroundService extends Service {
    private String savedString;

    public void onCreate() {
        System.out.println("Service created");
        super.onCreate();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("start command: ");
        savedString = intent.getStringExtra("myString);
        return super.onStartCommand(intent, flags, startId);
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onTaskRemoved(Intent rootIntent) {
        System.out.println("the saved string was: " + savedString);
        super.onTaskRemoved(rootIntent);
    }

    public void onDestroy() {
         System.out.println("destroyed service");
         super.onDestroy();
    }
}

然后我在其他班级有这个:

 Intent serviceIntent = new Intent(activity.getApplicationContext(), BackgroundService.class);
 serviceIntent.putExtra("myString", "this is my saved string");
 activity.startService(serviceIntent);

【问题讨论】:

  • 您需要创建一个服务来处理这个问题。它与您的视图/活动无关。当应用程序从最近的应用程序面板滑开时,它可以处理
  • “当我的应用程序关闭时”究竟是什么意思?您的意思是“当我的进程终止时”?你还有别的意思吗?
  • @CommonsWare 当进程终止时是。例如,当您打开正在运行的应用程序屏幕,然后滑动应用程序以使其停止运行。

标签: android android-activity android-service


【解决方案1】:

需要添加后台服务

public class BackgroundServices  extends Service
{


@Override
public void onCreate() {
    Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
    super.onCreate();
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {



}

@Nullable
@Override
public IBinder onBind(Intent intent) {

    return null;
}

@Override
public void onDestroy() {

    super.onDestroy();
}
}

然后在您的活动中。你想在哪里触发这个服务

使用

 startService(new Intent(getBaseContext(), BackgroundServices.class));

在您的情况下,它将调用该活动的 onDestory 函数

【讨论】:

  • 这似乎不起作用。我将发布我现在拥有的代码。
【解决方案2】:

进程终止时是的

这通常是不可能的。当进程终止时,您的应用中不会调用任何内容。

例如,当您打开正在运行的应用程序屏幕,然后滑动应用程序以使其停止运行时

这是一个任务删除。它可能会导致您的进程被终止,并且有许多方法可以终止您的进程,与任务删除无关。

要检测任务删除,请在 Service 中覆盖 onTaskRemoved()

【讨论】:

  • 你能看看我更新的帖子和我添加的代码吗?我创建了一个扩展 Service 的类,并通过调用 activity.startService() 启动它,但似乎没有调用该类中的任何内容。
  • @Ryan:嗯,该实现或您使用它的方式似乎不太正确。我建议您编写一个常规服务(即,摆脱StorableMethod 废话)并正确使用它(即,不要自己创建它的实例)。请务必在清单中注册服务。 the documentationthe JavaDocs 以及有关 Android 应用开发的书籍和课程中介绍了创建和使用服务。
  • 使用StorableMethods 为什么是我增加灵活性的方式。也因为有些变量需要从其他类中访问,这些类直到以后才会定义。添加StorableMethods 允许我在某些点创建Service,并使用所需的变量自定义方法,而无需将它们全部声明public static。一旦我将 Service 添加到清单中,一切正常,我忘记了。
  • 没关系,似乎当我设置方法时,方法中的代码永远不会被调用,因此我的想法毫无用处。所以我的问题是我如何实际使用其他类中的变量而不将它们全部设置public static。因为似乎以正确的方式执行此操作不允许我创建构造函数,所以我无法以这种方式传递变量。
  • 好的,在做了一些研究之后,我想我知道我应该怎么做,包括发送信息。我现在要添加代码,你介意检查一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多