问题
My service is not running is background when started manually and the app closed. I want to start the service automatically when my app is closed.
But in this example when I close the application it prints 'service created' then 'service destroyed' but not prints as 'service running' after 'service created'.
My service code.
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");
}
}
My Toaster for printing Toast message
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();
}
}
This service is called from onCreate() method.
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));
}
}
Below is my Manifest file.
<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>
My Configuration of android is below
- Android Studio 3.6.1
- Gradle 5.4.1
- Emulator API Level29
- Minimum SDK 21 Target 29
Help me to run my service in the background when the app is closed.
来源:https://stackoverflow.com/questions/61028239/service-is-not-running-in-background-when-app-is-closed-manually