这是我的代码:
@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();
}
}
它在Log中看起来不错,但应用程序没有响应。它看起来像这样:App doesn't respond 我是android的新手,我可以使用其他东西,听众吗? 我想跟踪我的CellID更改值,然后获取当前位置。
答案 0 :(得分:5)
onStartCommand
在UI线程上运行,这就是您的应用无法响应的原因。
您可以从Thread
开始onStartCommand
并执行实际任务。否则你可以去IntentService
参考 https://developer.android.com/reference/android/app/Service.html https://developer.android.com/reference/android/app/IntentService.html
答案 1 :(得分:1)
你有一个while (true)
Thread.sleep(3000);
所以它会冻结你的应用,因为它会在主UI线程上不断循环和等待。
您应该使用undertow as loadbalancer定期执行操作。
这是一个好的开始:AlarmManager
使用像while (true)
这样的循环通常是不好的做法。目前我只能想到的情况是在嵌入式系统中编程时使用它。
答案 2 :(得分:0)
利用intent服务在onHandleIntent()中运行while块以避免ANR(应用程序没有响应)。截至目前,您的代码正在阻止UI。
注意:在Android O中,当应用程序在后台启动服务时会抛出IllegalStateException。您必须使用Firebase作业调度程序而不是服务