Implement Broadcast receiver inside a Service
I will show you how to create SMS receiver in a service:
public class MyService extends Service {
@Override
public void onCreate() {
BwlLog.begin(TAG);
super.onCreate();
SMSreceiver mSmsReceiver = new SMSreceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(SMS_RECEIVE_ACTION); // SMS
filter.addAction(WAP_PUSH_RECEIVED_ACTION); // MMS
this.registerReceiver(mSmsReceiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
/**
* This class used to monitor SMS
*/
class SMSreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (TextUtils.equals(intent.getAction(), SMS_RECEIVE_ACTION)) {
//handle sms receive
}
}
}
It wouldn't be wise to check for the connectivity every second. Alternatively you can listen to the action (ConnectivityManager.CONNECTIVITY_ACTION) and identify if you are connected to an active network or not.
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Additionally you can check the network Type that is currently active(Type_WIFI, Type_MOBILE)
This way, you don't need a service that keeps checking the connectivity every second.