简体   繁体   English

当我关闭启动它的活动时,Android Service死亡

[英]Android Service dies in when I close the Activity that launched it

I'm trying to make an android app that launches a service which runs in the background while the app is open, and doesn't die when the app is closed. 我正在尝试制作一个可启动服务的android应用程序,该服务在应用程序打开时在后台运行,并且在应用程序关闭时不会消失。 However, my service does seem to die upon exit (or at some point, anyhow), because when I restart the app my check to see if the service is running is false. 但是,我的服务似乎确实会在退出时(或无论如何在某种程度上)消失,因为当我重新启动应用程序时,我检查服务是否正在运行是错误的。 My code: 我的代码:

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity {

  private ToggleButton enableButton;
  private boolean isRunning;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    enableButton = findViewById(R.id.enableButton);
    setRunning(MyService.running());
    enableButton.setChecked(isRunning);
    enableButton.setEnabled(true);
    enableButton.setClickable(true);
  }

  private void setRunning(boolean isRunning) {
    this.isRunning = isRunning;
  }

  public void onToggleEnable(View view) {
    boolean enabled = enableButton.isChecked();
    Intent intent = new Intent(this, MyService.class);
    if (enabled) startService(intent);
    else stopService(intent);
    setRunning(enabled);
  }

}

MyService.java MyService.java

public class MyService extends Service {

  private static boolean running = false;

  public static boolean running() {
    return running;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    running = true;
    return START_STICKY;
  }

  @Override
  public void onDestroy() {
    running = false;
  }

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

}

AndroidManifest.xml AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.chuckles.iscream">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="false" />
    </application>

</manifest>

activity_main.xml activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ToggleButton
            android:id="@+id/enableButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="32dp"
            android:onClick="onToggleEnable"
            android:textOff="@string/screamOff"
            android:textOn="@string/screamOn"
            android:layout_gravity="center_horizontal" />

    </LinearLayout>

</ScrollView>

strings.xml strings.xml

<resources>
    <string name="app_name">iScream</string>
    <string name="screamOn">Disable iScream</string>
    <string name="screamOff">Enable iScream</string>
</resources>

Your Service may killed by the System. 您的Service可能会被系统杀死。 From official doc: 从官方文档:

The Android system force-stops a service only when memory is low and it must recover system resources for the activity that has user focus. Android系统仅在内存不足时强制停止服务,并且必须为具有用户焦点的活动恢复系统资源。 If the service is bound to an activity that has user focus, it's less likely to be killed; 如果服务绑定到以用户为中心的活动,则它被杀死的可能性较小; if the service is declared to run in the foreground, it's rarely killed. 如果服务被声明为在前台运行,则很少被杀死。

So if you want to keep running your Service while your app is not open then your Service should be declared to run in the foreground . 因此,如果要在未打开应用程序的情况下继续运行Service ,则应声明Service 在前台运行 For this you have to call startForeground(ONGOING_NOTIFICATION_ID, notification); 为此,您必须调用startForeground(ONGOING_NOTIFICATION_ID, notification);

As stated here: 如此处所述:

https://developer.android.com/guide/components/services.html https://developer.android.com/guide/components/services.html

Caution: A service runs in the main thread of its hosting process; 注意:服务在其托管过程的主线程中运行; the service does not create its own thread and does not run in a separate process unless you specify otherwise. 除非另行指定,否则该服务不会创建自己的线程,也不会在单独的进程中运行。

Use an IntentService instead if you wish it to run in a seperate thread 如果希望它在单独的线程中运行,请改用IntentService

https://developer.android.com/guide/components/services.html#ExtendingIntentService https://developer.android.com/guide/components/services.html#ExtendingIntentService

The IntentService class does the following: IntentService类执行以下操作:

It creates a default worker thread that executes all of the intents that are delivered to onStartCommand(), separate from your application's main thread. 它创建一个默认的工作线程,该线程执行应用程序的主线程之外的所有传递给onStartCommand()的意图。

在清单文件中的服务标签中,只需添加:

android:process=":externalProcess"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM