Я создал сервис и он отлично отрабатывает как при запущенном так и при выключенном приложении. Но потом я узнал что он блокирует activity, так как отрабатывает в основном потоке. После запуска его в новом потоке он перестал работать после закрытия приложения. Вот код моего сервиса:
public class InetConnectionService extends Service {
final String channelId = "CHANNEL_ID";
final int id = 1;
NotificationManager notificationManager;
Intent intent;
PendingIntent pendingIntent;
public InetConnectionService() {
}
@Override
public void onCreate() {
super.onCreate();
notificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (hasConnection(getApplicationContext())) {
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(getApplicationContext(), channelId)
.setAutoCancel(false)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setContentTitle("title")
.setContentText("text")
.setPriority(PRIORITY_HIGH);
createChannelIfNeeded(notificationManager);
notificationManager.notify(id, notificationBuilder.build());
break;
}
}
stopSelf();
}
}).start();
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public boolean hasConnection(final Context context) {//проверяет подключение к интернету
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public void createChannelIfNeeded(NotificationManager manager) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
}