我有一个列表视图片段,其中填充了来自数组适配器的数据。列表视图的每个项目都包含一个按钮。我想这样做,当你按下按钮时,服务被初始化。我在CustomAdaptor类中实现了一个Receiver类及其on接收方法,
public class LikeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
String result=intent.getExtras().getString("result");
Toast t3 = Toast.makeText(context, result, Toast.LENGTH_LONG);
t3.show();
}
我已实施以下服务类
public class LikeService extends IntentService {
public LikeService() {
super("Like");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://api.fixer.io/latest?base=EUR&symbols="+"USD")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
JSONObject json = new JSONObject(response.body().string());
String code=intent.getAction();
double ratio = json.getJSONObject("rates").getDouble(code);
Intent i = new Intent("Like");
i.putExtra("result", ratio);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
以下方法位于Adapter类中,应该初始化服务
public void askLikes() {
Intent i = new Intent(context, LikeService.class);
String postid=Integer.toString(id);
context.startService(i);
}
在适配器的getView方法中定义的按钮的on Click侦听器如下:
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
askLikes();
LikeReceiver receiver = new LikeReceiver();
IntentFilter filter = new IntentFilter("Like");
LocalBroadcastManager.getInstance(context).registerReceiver(receiver, filter);
}
});
问题是,当我按下按钮时,吐司不会显示