【问题标题】:Can a notification to the status bar be called from an asynctask可以从异步任务中调用状态栏的通知吗
【发布时间】:2015-03-28 00:42:38
【问题描述】:

我是 Android 编程新手,对 Java 不是很熟悉。

我在活动中加载带有 webview 的 url,然后调用 asynctask 来解析来自 url 的文本。解析后,我想将其发布到状态栏并发出通知。在 doInBackground 之后,我将解析后的字符串传递给onPostExecute,但出现编译器错误。

  1. 不确定是否可以从以下位置调用 notificationcompat.builder onPostExecute 在 asynctask 中,或者如果需要从 活动。
  2. 在 doInBackground 之后会自动调用 onPostExecute 吗?

谢谢,克雷格

protected void onPostExecute(String mycontent) {
// set up for notification in the notification status bar
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(getApplicationContext())

.setSmallIcon(R.drawable.ic_stat_notify_lightning)
                        .setContentTitle("My Title Here")
                        .setContentText(mycontent);


        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, WebViewActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(WebViewActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        // Sets an ID for the notification
        int mNotificationId = 001;
// Gets an instance of the NotificationManager service
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
}

【问题讨论】:

    标签: java android android-asynctask


    【解决方案1】:

    onPostExecute会在doInBackground之后在主线程上被自动调用,你能告诉编译器错误的更多细节吗?

    【讨论】:

    • getApplicationContext() - 无法解析方法(这曾经是'this')
    • 我不确定输入错误行的最佳方法。大多数错误似乎源于我真的不明白的上下文(this)。另外,不确定主线程是什么意思。 WebViewActivity 是清单中的主要活动,我从那里调用(另一个类)我的 asynctask:_myasynctask.execute(); doInBackground
    • 尝试使用WebViewActivity.this.getApplicationContext()
    • 作为后续,我想使用 NotificationCompat 通过 Alarmmanager 和 BroadcastReceiver 发送通知,作为不在主要活动上的单独任务。通知包含从网页以指定时间间隔检索的信息。我可以使用什么来在 BroadcastReceiver 中执行此网络操作,因为 AsyncTask 想要在主要活动上被调用。我在这里搜索过,但没有找到解决方案。如果我应该将此作为一个新问题,请告诉我。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    相关资源
    最近更新 更多