Deploy a broadcast receiver inside a service

I want to check my internet connection while my android application is running. I tried to use services, but it seems that this is not the best option. Is there any possible way to implement a broadcast receiver in a service? or should I refuse the service and use only broadcast receivers? suggestions are welcome

thanks

+4
source share
4 answers

Now I will show how to create an SMS receiver in the 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 } } } 
+6
source

It would be unwise to check the connection every second. Alternatively, you can listen to the action ( ConnectivityManager.CONNECTIVITY_ACTION ) and determine if you are connected to an active network or not.

 IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 

In addition, you can check the type of network that is currently active (Type_WIFI, Type_MOBILE)

Thus, you do not need a service that checks the connection every second.

+2
source
+2
source

For this purpose you do not need to use Service or BroadCastReceiver . Just check the connection status every time you need to ping a server.

you can write a method that checks this and returns boolean (true / false) according to the state of the connection. The below method does the same.

 public static boolean isNetworkAvailable(Context mContext) { try { final ConnectivityManager conn_manager = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo network_info = conn_manager .getActiveNetworkInfo(); if (network_info != null && network_info.isConnected()) { if (network_info.getType() == ConnectivityManager.TYPE_WIFI) return true; else if (network_info.getType() == ConnectivityManager.TYPE_MOBILE) return true; } } catch (Exception e) { // TODO: handle exception } return false; } 
+1
source

Source: https://habr.com/ru/post/1479326/


All Articles