当我的设备改变手机连接时,我需要启动服务,我想可以使用下面的onCellLocationChanged()
实现,但只有在我收到来电时才会发出哔哔声…
我的听众:
public class CellLocationListener extends PhoneStateListener {
@Override
public void onCellLocationChanged(CellLocation location) {
super.onCellLocationChanged(location);
int cid = 0;
int lac = 0;
if (location != null) {
if (location instanceof GsmCellLocation) {
cid = ((GsmCellLocation) location).getCid();
lac = ((GsmCellLocation) location).getLac();
}
else if (location instanceof CdmaCellLocation) {
cid = ((CdmaCellLocation) location).getBaseStationId();
lac = ((CdmaCellLocation) location).getSystemId();
}
}
String cellInfo = Integer.toString(lac)+"-"+Integer.toString(cid);
Log.v("logg","CELL CHANGED:"+cellInfo);
}
}
我在main activity上使用了相同的cellinfo,当我启动它时,cellinfo会更改它的值,但是没有来自broadcas接收器的哔哔声……
在清单上:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
<receiver android:name="dado.auto3gdataswitch.CellChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
我的广播接收器
public class CellChangeReceiver extends BroadcastReceiver {
TelephonyManager telephony;
public void onReceive(Context context, Intent intent) {
CellLocationListener phoneListener = new CellLocationListener();
telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, CellLocationListener.LISTEN_CALL_STATE);
Toast.makeText(context, "ON receiver", Toast.LENGTH_LONG).show();
final MediaPlayer mp = MediaPlayer.create(context, R.raw.beep);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
}
});
Log.v("logg","onreceiver");
}
}
我只在接到来电时听到哔哔声,换手机时听不到。
发生了什么?是吗?
最佳答案
您正在收听CellLocationListener.LISTEN_CALL_STATE
,但您应该收听CellLocationListener.LISTEN_CELL_LOCATION
。如果您希望在单元格更改时播放声音,则应将相应的代码移动到onCellLocationChanged
。只有在接收到android.intent.action.PHONE_STATE
时,才会注册您的单元格更改侦听器。
关于android - onCellLocationChanged问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23676679/