当我在我的服务中的onStartCommand()中运行while循环时,应用程序没有响应

Gor*_*čić 0 android listener android-intent

这是我的代码:

 @Override
public void onCreate() {
    super.onCreate();
    //Log.i("TAG", "ovdje smo");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("alo", "bre");
     telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
     cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
    oldCellID = cellLocation.getCid();

    while( true ){
        Log.i("jesmo li tu",""+oldCellID);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        Toast.makeText(this, "Kupimo cell ID OLD" + oldCellID, Toast.LENGTH_SHORT).show();
        telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
        newCellID = cellLocation.getCid();

        if(oldCellID != newCellID){
            //TODO uzmi lokaciju + spremi u bazu
            Log.i("usli u petlju", "DA"+newCellID + oldCellID);
            Toast.makeText(this, "Stari id ->" + oldCellID + " noviCellID -> " + newCellID, Toast.LENGTH_SHORT).show();
            oldCellID = newCellID;
            telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
            newCellID = cellLocation.getCid();
        }


    }
Run Code Online (Sandbox Code Playgroud)

它在Log中看起来不错,但应用程序没有响应.它看起来像这样:应用程序没有响应 我是android的新手,我可以使用别的东西,听众?我想跟踪我的CellID更改值,然后获取当前位置.

小智 5

onStartCommand在UI线程上运行,这就是你的应用没有响应的原因.要么你就可以开始ThreadonStartCommand和执行实际任务.否则你可以去IntentService

请参阅 https://developer.android.com/reference/android/app/Service.html https://developer.android.com/reference/android/app/IntentService.html