Android:在应用程序最终关闭时运行它

时间:2016-12-21 18:35:15

标签: java android background

我注意到,当我最终关闭我的应用时,类runInBackGround的方法MultiplyTask停止工作。它在活动处于阶段STOPPAUSE时有效,但当我关闭我的应用时,该方法结束(它是使用周期while(true) {...}创建的循环)。 例如Whatsapp如何发送通知虽然它已经关闭了?我想创造一个类似的东西。谢谢!

2 个答案:

答案 0 :(得分:0)

Asynctask非常适合需要在后台执行的短操作。通常Asyntask被实现为活动的子类,当app关闭时会被销毁。它还在某些时候与UI线程进行通信......所以它需要活动在内存中...对于长时间运行的操作,服务更好。有些应用程序会在用户未运行时通知用户。实际上,他们有一个或多个后台运行的服务。您可以在手机设置 - >应用菜单中看到这些内容。 有关服务的更多信息,请参阅this

答案 1 :(得分:0)

当应用关闭时,所有代码都将停止运行。如果您希望在应用程序打开时执行并在应用程序关闭时继续执行代码,您将需要查看using a Service.

仔细查看服务文档,它有望成为您的目标。 您的应用关闭时服务也会被终止,但使用START_STICKY返回值可以确保您的服务在终止时重新启动。

编辑更多信息:

<service
    android:name="MyService" />

将以上内容添加到AndroidManifest.xml

public class MyService extends Service {

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
          // This is where you would place your code that you want in the background
          // Putting your while loop here will make sure it runs when the app is closed
          return Service.START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
        //TODO for communication return IBinder implementation
    return null;
  }
}

使用上面的代码创建一个新类。

Intent i= new Intent(context, MyService.class);
startService(i);

在启动应用程序时,从启动器Activity调用此代码启动服务。

希望这有帮助!