我检查了this question ,但它似乎没有回答我的问题,这个问题涉及的少得多。我在主进程中从菜单项调用 IntentService。它目前只是一个骨架,它在 onHandleIntent() 中放置一个 Toast,它最终应该在处理结束时短暂出现,表示它已完成。但是它会永远保留在屏幕上(即使应用程序已停止)。我用模拟器和我的 Galaxy S2 进行了测试,结果相同。有人能给我指出正确的方向吗?
这是服务代码:
package com.enborne.spine;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class SaveFile extends IntentService {
private final String TAG = "SaveFile";
public SaveFile() {
super("SaveFile");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service Started.. ");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service Destroyed.. ");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "HandleIntent");
// File saved
Toast.makeText(this, "File has been saved", Toast.LENGTH_SHORT).show();
}
}
(onCreate 和 onDestroy 重写只是暂时用于登录 Eclipse,这样我就可以看到发生了什么。)
因此,我从一个 Activity 的菜单中调用它(混淆上下文只是因为服务没有启动——一些白痴忘记将它包含在 list 中!):
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.id.chart:
i = new Intent(getBaseContext(), Chart.class);
i.putExtra(KEY_CENTRE_LAT, mCentreLat); // centre coordinate
i.putExtra(KEY_CENTRE_LONG, mCentreLong); // centre coordinate
i.putExtra(KEY_RADIUS, mRadius); // effective radius
startActivity(i);
break;
case R.id.save:
Log.d("SaveFile", "Starting service...");
// i = new Intent(getBaseContext(), SaveFile.class);
i = new Intent(this, SaveFile.class);
startService(i);
break;
}
return true;
}
编辑:我找到了 this article ,这或许能说明问题。引用一句话:
However, you can only use Toast in the main GUI thread, or else you run into problems where the Toast message doesn't disappear after a period (because the main GUI context doesn't know anything about Toast messages used in a separate thread context).
最佳答案
在我的编辑中链接到的文章将我带到了 this blog这解决了我的问题。我没有在其他地方看到您不能直接从服务发出 toast 。所以我的 onHandleIntent 现在看起来像这样:
private Handler handler;
@Override
protected void onHandleIntent(Intent intent)
{
Log.d(TAG, "onHandleIntent");
/* Stripped out some code here that I added later to keep it similar to
* my example above
*/
handler.post(new Runnable()
{
// @Override
public void run()
{
Toast.makeText(getApplicationContext(), "File has been saved",
Toast.LENGTH_SHORT).show();
}
}); // Display toast and exit
}
(如果有人能解释为什么我必须注释掉 run() 上的 @Override 以避免错误,我将不胜感激。我的应用程序中还有其他几个地方我必须这样做。)
编辑:我刚刚找到 this post这实际上是一回事。我不知道我以前是怎么错过的。
关于Android:来自 IntentService 的 Toast 永远保留在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12407910/