我正在实现一个广播接收器,它可以读取传入的SMS。之后,我要调用一个运行良好的API。当我收到响应时,我想通过onSuccess方法在屏幕上显示一条敬酒消息(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);
}
}
答案 0 :(得分:0)
制作构造函数并将上下文传递给它。
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);
}
}