views:

78

answers:

3

HelloZz,

I need to find a way to measure the current signal strength of Android phone, without the need to register a PhoneStateListener that God knows when it returns the actual asu.

something like:

int signal = getPhoneSignal();

any help plz?

thanks!

+1  A: 

I don't think there is a way to do it directly. But you could register the PhoneStateListener and save the last updated value into a variable and return/call this.

Tseng
i tried to do that:Activity is called from main threadPhoneStateListener is updated from main threadi cant get Activity to wait for PhoneStateListener to save its first signal value... im having a deadlock :S
Shatazone
+1  A: 

If you will have a closer look on Android sources you will see that after registering PhoneStateListener you will have instant notification:

public void listen(PhoneStateListener listener, int events) {
        String pkgForDebug = mContext != null ? mContext.getPackageName() : "<unknown>";
        try {
            Boolean notifyNow = (getITelephony() != null);
            mRegistry.listen(pkgForDebug, listener.callback, events, notifyNow);
        } catch (RemoteException ex) {
            // system process dead
        }
    }

So you can create your own timer and on timer update register new listener and after receiving instant update remove it by passing the same listener object and set the events argument to LISTEN_NONE.

Of course I can't call it best practice but the only alternative I can see is to calculate signal strength by yourself based on signal strengths from getNeighboringCellInfo().

p.s. Not only God knows when PhoneStateListener will be triggered ;)

cement
A: 

thanks for ur answer cement... i already tried this:

int asu = -9999;
private void getSignalStrength(){

    final TelephonyManager Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
    PhoneStateListener listener = new PhoneStateListener(){         
        @Override
        public void onSignalStrengthChanged(int asu) {
            Main.this.asu = asu;
            Tel.listen(this, PhoneStateListener.LISTEN_NONE);
        }
    };

    Tel.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
    System.out.println("Signal: " + asu);
}

and its giving me: Signal: -9999

which means that the phone state listener was not notified instantly

Shatazone
Instant doesn't mean real-time. Your code will not work because getSignalStrength method will complete execution before listener will be triggered. At at the moment of System.out.println asu will not yet be changed. However you can implement custom class that will use thread-synchronization to return sync result.
cement