手动关闭应用程序后,服务未在后台运行

时间:2020-04-04 12:42:42

标签: android service background-service

手动启动并关闭应用程序后,我的服务未运行,处于后台状态。我想在我的应用关闭时自动启动服务。

但是在此示例中,当我关闭应用程序时,它会打印“服务已创建”,然后打印“服务已损坏”,但不会在“服务已创建”之后打印为“服务正在运行”。

我的服务代码。

public class DataChangeService extends Service {
    Toaster toaster; //

    @Override
    public void onCreate() {
        super.onCreate();
        toaster = new Toaster(getApplication());
        toaster.showMsg("service created");

    }

    public IBinder onBind(Intent intent) {
        return null;

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        toaster.showMsg("Service is running");
        return START_STICKY;
    }

    public void onDestroy() {
        super.onDestroy();

        toaster.showMsg("service destroyed");
    }
}

我的烤面包机,用于打印Toast消息

public class Toaster {
    Context context;
    public Toaster(Context context){
        this.context=context;
    }
    public void showMsg(String msg)
    {
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    }
}

此服务是通过onCreate()方法调用的。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService(new Intent(MainActivity.this,DataChangeService.class));

        }
    }

以下是我的清单文件。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.selfish.servicex">

    <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=".DataChangeService" android:exported="true" android:enabled="true"/>
    </application>
</manifest>

“我的android配置”如下

  • Android Studio 3.6.1
  • 5.4.1级
  • 仿真器API级别29
  • 最低SDK 21目标29

关闭应用程序后,帮助我在后台运行我的服务。

0 个答案:

没有答案