package org.meicode.startedservices;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, SecondExampleService.class);
intent.putExtra("number", 5);
startService(intent);
startService(intent);
stopService(intent);
}
}
package org.meicode.startedservices;
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import androidx.annotation.Nullable;
public class ExampleService extends IntentService {
private static final String TAG = "ExampleService";
public ExampleService() {
super("DownloadThread");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
try{
int number = intent.getIntExtra("number", -1);
if (number != -1) {
for (int i=0; i<number; i++) {
Log.d(TAG, "onHandleIntent: number: " + i);
SystemClock.sleep(1000);
}
}
}catch (NullPointerException e) {
e.printStackTrace();
}
}
}
package org.meicode.startedservices;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import androidx.annotation.Nullable;
public class SecondExampleService extends Service {
private static final String TAG = "SecondExampleService";
private int serviceId = -1;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.serviceId = startId;
try {
final int number = intent.getIntExtra("number", -1);
if (number != -1) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<number; i++) {
Log.d(TAG, "onHandleIntent: number: " + i);
SystemClock.sleep(1000);
}
}
});
thread.start();
}
}catch (NullPointerException e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
stopSelf(serviceId);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.meicode.startedservices">
<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=".ExampleService"
android:exported="false"
android:description="@string/service_desc"/>
<service android:name=".SecondExampleService"
android:exported="false"
android:description="@string/service_desc"/>
</application>
</manifest>