0

This is my code:

 @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();
        }


    }

It looks good in Log, but app doesn't response. It looks like this: App doesn't respond I'm new at android, Can I use something else, listener ?? I want to track when my CellID change value and then get current location.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
Goran Belačić
  • 81
  • 2
  • 10

3 Answers3

6

onStartCommand runs on UI Thread, That's why your app doesn't respond. Either you can start a Thread from onStartCommand and execute the actual task. Otherwise you can go for IntentService

Refer https://developer.android.com/reference/android/app/Service.html https://developer.android.com/reference/android/app/IntentService.html

VishnuSP
  • 599
  • 5
  • 16
1

You have a while (true) with a Thread.sleep(3000); so it's freezing your app because it keeps looping and waiting on the main UI thread.

You should use an AlarmManager to do things periodically.

Here is a good start: Alarm Manager Example

Using loops like while (true) is generally bad practice. Only situation I can think of at the moment is using it when programming in embedded systems.

Denny
  • 1,766
  • 3
  • 17
  • 37
0

Make use of intent service to run the while block in onHandleIntent() to avoid ANR(application not responding). As of now your code is blocking UI.

Note : In Android O, starting a service while application is in background will throw IllegalStateException. You have to use Firebase Job dispatcher instead of Service

adarsha nayak v
  • 306
  • 1
  • 9