我正在编写一个作为前台服务在后台运行的应用程序。此服务实例化 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 上测试