我知道存在这样的问题,但我在这里很困惑.我正在使用此代码:
public class NewWaitAppActivity extends Activity {
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler = new Handler();
lcmgr = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Thread LocThread = new Thread(mLocationUpdater);
Log.d("TAG","About to start worker thread");
LocThread.start();
}
public void startTimer(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = System.currentTimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
TextView timer = (TextView) findViewById(R.id.time_elapsed);
if (seconds < 10) {
timer.setText("" + minutes + ":0" + seconds);
} else {
timer.setText("" + minutes + ":" + seconds);
}
mHandler.postDelayed(this, 1000);
}
};
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
mStopTimer();
}
};
private Runnable mLocationUpdater = new Runnable(){
public void run(){
Log.d("TAG","Inside worker thread");
lcmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
};
}
Run Code Online (Sandbox Code Playgroud)
我基本上试图在位置更新时停止主线程的计时器.应用程序甚至没有启动,它在运行时给出了上面提到的错误.该错误是由requestLocationUpdates()引起的.好像我不能在onLocationChanged()中调用stopTimer().我怎么能纠正这个?
小智 60
甚至不需要编写复杂的解决方案:
locationManager.requestLocationUpdates(provider, 5000, 0, mylistener, Looper.getMainLooper());
Run Code Online (Sandbox Code Playgroud)
这将工作得很好.
当它本身是一个基于异步回调的机制时,是否需要从你创建的线程中调用"lcmgr.requestLocationUpdates(....)"?
只需在活动的onCreate()中移动此代码,事情应该可以正常工作.
当你尝试在线程中创建一个根本不打算循环的处理程序(即不调用Looper.prepare的线程,因为你的堆栈跟踪状态也是如此)时,会出现此错误.
有关此错误的更多说明也可以在此站点中找到.
但这里也给出了一个很好的解释.
http://www.aviyehuda.com/2010/12/android-multithreading-in-a-ui-environment/
| 归档时间: |
|
| 查看次数: |
11269 次 |
| 最近记录: |