后台进程完成Android后显示通知

时间:2013-01-19 01:17:54

标签: java android multithreading http-request loopj

我正在使用loopj HTTP CLIENT在后台加载HTTP请求,当它完成时,我想显示“成功”通知(对话框,吐司等)

我将代码放在一个单独的(非活动)类中,并使用一个执行后台请求的静态方法。最后,响应位于onSuccess方法下的AsyncHttpResponseHandler中。在这种方法中,我可以打印出响应,确认请求已通过,将数据保存到SD卡/共享首选项,但如何访问UI线程以显示通知?

提前致谢。

3 个答案:

答案 0 :(得分:3)

您可以使用Handler或致电Activity.runOnUiThread()来完成此操作。所以您要么将HandlerActivity对象传递给静态方法,然后在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!
    }
  }
);

答案 1 :(得分:1)

我猜你的意思是服务作为后台进程。服务有许多内置方法,如onCreateonStartCommandonDestroy等。我建议使用通知,因为通知不需要UI线程来完成工作。

创建一个生成通知的方法,并在HTML读取结束后调用它。

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);
}

答案 2 :(得分:0)

您可以使用该消息触发本地广播,并使用接收者显示祝酒词。

在进行更新的班级中执行此操作:

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 / create UI的上下文,这仍然有效。

相关问题