//This is your service class working fine just add network state permission in your manifest and at runtime
public class MyService extends Service {
private static final String TAG = "MyService";
private ServiceHandler serviceHandler;
private static final int MSG_REQUEST = 1112;
static Context context1;
public static void startService(Context context) {
context1=context;
Intent myIntent = new Intent(context, MyService.class);
context.startService(myIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class ServiceHandler extends Handler {
ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_REQUEST:
checkNetwork();
break;
}
}
}
private void checkNetwork() {
ConnectivityManager cm = (ConnectivityManager)context1.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
String networkType = "";
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d("yahooooooo","WIFI");
}
else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
networkType = "mobile";
Log.d("yahooooooo","MOBILE");
}
if (!serviceHandler.hasMessages(MSG_REQUEST)) {
serviceHandler.sendEmptyMessageDelayed(MSG_REQUEST, 1000);//every 1 sec
}
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread handlerThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
handlerThread.start();
serviceHandler = new ServiceHandler(handlerThread.getLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!serviceHandler.hasMessages(MSG_REQUEST)) {
serviceHandler.sendEmptyMessage(MSG_REQUEST);
}
return START_REDELIVER_INTENT;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
PendingIntent service = PendingIntent.getService(
getApplicationContext(),
1001,
new Intent(getApplicationContext(), MyService.class),
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
}
}
// Теперь звоните в сервис из Activity
MyService.startService(MainActivity.this);
// В манифесте
<service
android:name=".MyService"
tools:ignore="InnerclassSeparator" />