2010-10-08 52 views
1

我需要找到一种方法来测量Android手机的当前信号强度,而不需要注册一个PhoneStateListener,神知道它什么时候返回实际的asu。即时信号强度

类似:

int signal = getPhoneSignal(); 

任何帮助PLZ?

谢谢!

+0

你可以试试我的解决方案,看看它的工作? – 2013-07-14 14:22:10

回答

1

我不认为有办法直接做到这一点。但是您可以注册PhoneStateListener,并将最新更新的值保存到一个变量中并返回/调用它。

+0

我想这样做: 活动是由主线程调用 PhoneStateListener从主线程 更新我不能让活动等待PhoneStateListener保存其第一信号值...有死锁IM:S – Shatazone 2010-10-08 11:03:53

2

如果你有在Android源仔细看你会发现注册PhoneStateListener后,你将有即时通知:

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 
     } 
    } 

所以,你可以创建自己的计时器和定时器更新注册新的监听器和后接收即时更新通过传递相同的侦听器对象并将events参数设置为LISTEN_NONE来删除它。

当然,我不能称之为最佳做法,但我可以看到的唯一选择是根据来自getNeighboringCellInfo()的信号强度自行计算信号强度。

p.s. Not only God knowsPhoneStateListener将被触发;)

0
class Signal { 

    static volatile CountDownLatch latch; 
    static int asu; 
    private final static String TAG = Signal.class.getName(); 

    int getSignalStrength(Context ctx) throws InterruptedException { 
     Intent i = new Intent(TAG + ".SIGNAL_ACTION", Uri.EMPTY, ctx, 
       SignalListenerService.class); 
     latch = new CountDownLatch(1); 
     asu = -1; 
     ctx.startService(i); 
     Log.w(TAG, "I wait"); 
     latch.await(); 
     ctx.stopService(i); 
     return asu; 
    } 
} 

其中:

public class SignalListenerService extends Service { 

    private TelephonyManager Tel; 
    private SignalListener listener; 
    private final static String TAG = SignalListenerService.class.getName(); 

    private static class SignalListener extends PhoneStateListener { 

     private volatile CountDownLatch latch; 

     private SignalListener(CountDownLatch la) { 
      Log.w(this.getClass().getCanonicalName(), "CSTOR"); 
      this.latch = la; 
     } 

     @Override 
     public void onSignalStrengthChanged(int asu) { 
      Signal.asu = asu; 
      latch.countDown(); 
     } 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.w(TAG, "Received : " + intent.getAction()); 
     Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
     listener = new SignalListener(Signal.latch); 
     @SuppressWarnings("deprecation") 
     final int listenSs = PhoneStateListener.LISTEN_SIGNAL_STRENGTH; 
     Tel.listen(listener, listenSs); 
     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     Log.w(TAG, "onDestroy"); 
     Tel.listen(listener, PhoneStateListener.LISTEN_NONE); 
     super.onDestroy(); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 
} 

这是工作的代码。不要忘记在清单中注册您的服务并获取权限。有可能有更好/更优雅的方式来做到这一点,所以欢迎评论/更正。