1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
package io.ionic.starter;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.net.wifi.WifiManager;
import android.content.Context;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.annotation.Nullable;
public class MyService extends Service {
private PowerManager.WakeLock wakeLock;
private WifiManager.WifiLock wifiLock;
private static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag");
wakeLock.acquire(14400000); // 4h
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "MyApp::MyWifiLock");
wifiLock.acquire();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("mesRadios")
.setContentText("L'application est en cours d'exécution...")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build();
startForeground(1, notification);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// Arrête le service en avant-plan et retire la notification
stopForeground(true);
// Libère les verrous WakeLock et WifiLock
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
}
if (wifiLock != null && wifiLock.isHeld()) {
wifiLock.release();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Service en avant-plan",
NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopSelf();
}
} |
Partager