我正在编写一个在后台作为前台服务运行的应用程序。此服务实例化PhoneStateListener的子类。PhoneStateListener使用前台服务的上下文对象创建TelephonyService,然后监听单元位置更改。当显示开启时,这个操作完全正常。但是一旦显示关闭,单元格日志记录就无法继续工作。
public class gps_service extends Service
{
public static TelephonyManager p_TelephonyManager = null;
public static myPhoneStateListener p_myPhoneStateListener = null;
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
p_myPhoneStateListener = new myPhoneStateListener();
p_TelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
p_TelephonyManager.listen(p_myPhoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION);
...
}
public class myPhoneStateListener extends PhoneStateListener
{
public static int CurrentCellID;
/*
public static int current_cell_id;
@Override
public void onCellLocationChanged(CellLocation p_CellLocation)
{
//write to log
}
}
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
当手机屏幕开启时,一切正常,但是当关闭屏幕后,onCellLocationChanged事件从未被调用。我尝试了以下代码:
GsmCellLocation currentCellLocation = (GsmCellLocation) p_TelephonyManager .getCellLocation();
但是这段代码总是返回屏幕关闭前的上一个小区ID,而不是实际的小区ID。
我还在我的服务中尝试使用partial_wake_lock,但结果相同:
private PowerManager pPowerManager = null;
private PowerManager.WakeLock pWakeLock = null;
..
@Override
public void onCreate()
{
super.onCreate();
pPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
pWakeLock = pPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "No sleep");
pWakeLock.acquire();
...
}
@Override
public void onDestroy()
{
if (pWakeLock != null)
{
pWakeLock.release();
pWakeLock = null;
}
...
}
有任何想法我做错了什么吗?在HTC Desire Z Android 2.2上进行测试。