For finding the Signal Strength I made the following changes in my project, So i will raise a API request if signal strength is good. If poor, we will prompt to user regarding the internet connection. But this code is working only for single sim device, not works for dual sim and not getting "ASU" and "dBm" value for secondary sim. Anyone knows how will detect the signal strength for dual sim.
My Project minSdkVersion = 16 and targetSdkVersion=23
Code for your references.
Mainactivity.java
Thread t1 = new Thread()
{
public void run()
{
Intent service1 = new Intent(HomeScreen.this, SignalService.class);
startService(service1);
}
};
SignalService.Java
public class SignalService extends Service {
private static final String TAG = "SignalService" ;
private TelephonyManager mTelephonyManager;
private PhoneStateListener mPhoneStateListener;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
mPhoneStateListener = new PhoneStateListener(){
public static final int INVALID = Integer.MAX_VALUE;
public int signalStrengthDbm = INVALID;
public int signalStrengthAsuLevel = INVALID;
public int getGsmLevel = INVALID;
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
signalStrengthDbm = getSignalStrengthByName(signalStrength, "getDbm");
signalStrengthAsuLevel = getSignalStrengthByName(signalStrength, "getAsuLevel");
getGsmLevel = getSignalStrengthByName(signalStrength, "getGsmLevel");
Log.d(TAG, "Signal Strength Full Log = " + signalStrengthDbm);
Log.d(TAG, "Signal Strength Full Log = " + signalStrengthAsuLevel);
}
private int getSignalStrengthByName(SignalStrength signalStrength, String methodName) {
try {
Class classFromName = Class.forName(SignalStrength.class.getName());
java.lang.reflect.Method method = classFromName.getDeclaredMethod(methodName);
Object object = method.invoke(signalStrength);
return (int) object;
} catch (Exception ex) {
return INVALID;
}
}
};
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Register the listener here.
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS|PhoneStateListener.LISTEN_SERVICE_STATE);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}