1
我目前正试图显示从IntentService,如果设备检测到加速度计吐司。为此,我搜索并了解到我可以实施处理程序。但是,它不是很有效。该代码编译并在模拟器上运行时没有任何错误,但吐司不显示。我想知道是否可以帮助我发现代码中的错误。代码如下所示。Totent从IntentService发布与处理程序不会显示何时在onHandleIntent中创建处理程序
任何帮助,将不胜感激!
public class AccelService extends IntentService implements SensorEventListener{
private SensorManager mySensorManager;
private Handler toastHandler;
public AccelService(){
super("AccelerometerIntentService");
}
...
private class ToastRunnable implements Runnable{
String toastText;
public ToastRunnable(String text){
toastText = text;
}
@Override
public void run(){
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onHandleIntent(Intent intent){
toastHandler = new Handler();
initialize();
}
public void initialize(){
mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if(mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){
toastHandler.post(new ToastRunnable("Accelerometer Detected!"));
}
}
...
}
http://stackoverflow.com/questions/5346980/intentservice-wont-show-toast?rq=1 – marcinj
记录如果runnable被执行并尝试getBaseContext()作为上下文参数 – Sam
@ marcin_j:我不太确定解决建议的帖子是正确的。 IntentService引用提到'onStartCommand'方法不会被覆盖。此外,Handler的全部意义在于IntentService在不同的线程中运行并作为解决方案。 – ElectroJunkie