我创建了一个意图下载服务,我想将下载数据传递给Toast并在主要活动中传递给Text。下载服务应该反复从警报管理器开始。我该怎么做呢?
目前,它没有在Toast中显示,但我有网络流量;数据已下载但未显示。
相关代码:
public class DownloadService extends IntentService {
public String response;
public DownloadService() {
super("DownloadService");
}
// Will be called asynchronously be Android
@Override
protected void onHandleIntent(Intent intent) {
//String urldown = intent.getStringExtra("url");
String urldown="http://......";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urldown);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (IOException e) {
e.printStackTrace();
}
Intent intentsend=new Intent("update");
intentsend.putExtra( "downdata",response);
sendBroadcast(intentsend);
}
答案 0 :(得分:1)
可以使用BroadcastReceiver
:
在您的活动中,添加以下代码:
private BroadcastReceiver updateReceiver;
//...
@Override
protected void onResume() {
super.onResume();
updateReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//get extras, do some stuff
}
};
IntentFilter updateIntentFilter=new IntentFilter("update");
registerReceiver(updateReceiver, updateIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
if (this.updateReceiver!=null)
unregisterReceiver(updateReceiver);
}
然后,在您的IntentService
中,只需使用相同的动作发送广播:
Intent intent=new Intent("update");
intent.putExtra(...);
sendBroadcast(intent);
答案 1 :(得分:0)
对于我个人来说,接收器没有工作,所以我创建了一个单例类,我使用setter方法设置变量,使用getter方法将它们带到特定的活动。