【问题标题】:Calling Toast method inside onSuccess在 onSuccess 中调用 Toast 方法
【发布时间】:2019-11-08 16:30:37
【问题描述】:

我正在实现一个广播接收器,它读取传入的 SMS。之后,我调用了一个运行良好的 API。当我得到响应时,我想通过 onSuccess 方法在屏幕上显示一条 toast 消息(onSuccess)。

我尝试了几次迭代,但没有任何结果。

@Override
public void onReceive(Context context, Intent intent) {
//other code...

new NetworkAccess().execute(url); => Calling NetworkAccess, Passsing the URL here. //

}

public class NetworkAccess extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... urls) {

          // API call here //

         public void onSuccess(int statusCode, Header[] headers, JSONObject response) {  
             // Toast Message goes here//

        }
        });
        return null;
    }

     @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }

}

【问题讨论】:

  • 您遇到什么错误?

标签: android api android-asynctask background-process android-toast


【解决方案1】:

创建构造函数并将上下文传递给它。

public class NetworkAccess extends AsyncTask<String, Void, Integer> {

    private Context mContext;

    public NetworkAccess(Context context) {
        this.mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected Integer doInBackground(String... urls) {
        //API call goes here//
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers,   JSONObject response) {
         Toast.makeText(mContext, "Your message goes here.", Toast.LENGTH_SHORT).show();
        //API response comes here. I want to send an alert to the user after reading the response.//
    }

    @Override
    protected void onPostExecute(Integer aVoid) {
        super.onPostExecute(aVoid);
    }
}

【讨论】:

  • 嗨 Dhaval,我实现了代码并以这种方式调用了 NetworkAccess 类 new NetworkAccess(context).execute(hyperlink);在广播接收器中。它仍然没有显示 Toast 消息。还有其他建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-25
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多