我正在使用loopj HTTP CLIENT在后台加载一个 HTTP 请求,完成后,我想显示一个“成功”通知(对话框、toast 等)
我将代码放在一个单独的(非活动)类中,该类具有执行后台请求的静态方法。最后,响应位于 onSuccess 方法下的 AsyncHttpResponseHandler 中。在这种方法中,我可以打印出响应,确认请求通过,将数据保存到 sd 卡/共享首选项,但是如何访问 UI 线程以显示通知?
提前致谢。
我正在使用loopj HTTP CLIENT在后台加载一个 HTTP 请求,完成后,我想显示一个“成功”通知(对话框、toast 等)
我将代码放在一个单独的(非活动)类中,该类具有执行后台请求的静态方法。最后,响应位于 onSuccess 方法下的 AsyncHttpResponseHandler 中。在这种方法中,我可以打印出响应,确认请求通过,将数据保存到 sd 卡/共享首选项,但是如何访问 UI 线程以显示通知?
提前致谢。
您可以使用 aHandler
或调用Activity.runOnUiThread()
. 所以你要么将一个Handler
, 或一个Activity
对象传递给你的静态方法,然后在你的onSuccess()
方法中,做,
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// i'm on the UI thread!
}
}
);
或者,
handler.post(new Runnable() {
@Override
public void run() {
// i'm on the UI thread!
}
}
);
我猜你的意思是作为后台进程的服务。服务有许多内置方法,如onCreate
、onStartCommand
、onDestroy
等。我建议使用通知,因为通知不需要 UI 线程来完成这项工作。
Create a method to generate a notification and call it after your HTML read is over.
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
您可以使用消息触发本地广播,并使用接收器显示敬酒。
在进行更新的课堂上执行此操作:
Intent intent = new Intent("ACTION_TOAST");
intent.putExtra("message", "Success!");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
然后在任何可能想了解更新的活动中,执行以下操作:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if ("ACTION_TOAST".equals(intent.getAction()) {
Toast.makeText(MyActivity.this, intent.getStringExtra("message"),
Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(
receiver, new IntentFilter("ACTION_TOAST"));
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
您仍然需要将上下文传递给您的静态方法,但即使该上下文是服务或其他无法显示 Toast/创建 UI 的上下文,这仍然有效。