У меня есть класс обслуживания, который я хочу использовать для проверки интернета, когда приложение закрыто, и в фоновом режиме. Если приложение подключено к сети, метод будет вызываться из класса обслуживания. Это код службы
public class MyService extends Service {
public MyService() {
}
NotificationCompat.Builder builder;
private FirebaseAuth.AuthStateListener mAuthListener;
static final String CONNECTIVITY_CHANGE_ACTION="android.net.conn.CONNECTIVITY_CHANGE";
@Nullable
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
// throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
Toast.makeText(getApplicationContext(), "checking for new bookings", Toast.LENGTH_SHORT).show();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
if (!ConnectionHelper.isConnectedOrConnecting(context)) {
if (context != null) {
boolean show = false;
if (ConnectionHelper.lastNoConnectionTs == -1) {
show = true;
ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
} else {
if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
show = true;
ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
}
}
if (show && ConnectionHelper.isOnline) {
ConnectionHelper.isOnline = false;
Log.i("NETWORK123", "Connection lost");
}
}
} else {
Log.i("NETWORK123", "Connection lost");
ConnectionHelper.isOnline = true;
Methodwhenappisonline();
}
}
}
};
registerReceiver(receiver,filter);
return START_STICKY;
}
@Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(getApplicationContext(),"service killed ",Toast.LENGTH_SHORT).show();
}}
Ниже приведен класс помощника подключения
public class ConnectionHelper {
public static long lastNoConnectionTs=-1;
public static boolean isOnline=true;
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
public static boolean isConnectedOrConnecting(Context context){
ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork=cm.getActiveNetworkInfo();
return activeNetwork!=null&&activeNetwork.isConnectedOrConnecting();
// activeNetwork.isConnectedOrConnecting();
}
}
А ниже - мой манифест
<service
android:name=". MyService"
android:enabled="true"
android:exported=true></service
Служба предназначена для запуска приложения в фоновом режиме и при его закрытии. Однако, когда приложение находится в фоновом режиме, оно через некоторое время уничтожается, а когда оно закрывается, оно мгновенно уничтожается. Пожалуйста помоги. Обратите внимание, что моя минимальная версия SDK составляет 16