来自后台

时间:2016-04-30 21:25:05

标签: java android android-intent

我创建了一个Intent服务,我从NotificationChecker.java调用它扩展了Broadcast接收器。我想要做的是在后台以固定的时间间隔我想从URL下载文本并向该字符串干杯。在意向服务中,我正在从URL读取数据,但它没有收到任何数据。这是我的示例代码。

package com.jamiahamdard.hammad.noticeboard;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


public class MyIntentService extends IntentService {

String finalJson="ygf";
private Handler handler;
Context context;
public MyIntentService() {
    super("MyIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {

    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
URL url=new URL("http://sig.ieeejamiahamdard.org/notice_board/notices.txt");
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        finalJson = buffer.toString();
Toast.makeText(getApplicationContext(), finalJson,Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
   }


  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
  onHandleIntent(intent);
    return super.onStartCommand(intent, flags, startId);
 }

}

和广播接收器

package com.jamiahamdard.hammad.noticeboard;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NotificationChecker extends BroadcastReceiver {


SharedPreferences student;
String finalJson;
Context mycontext;
Intent intent;
public NotificationChecker() {
}

@Override
public void onReceive(Context context, Intent intent) {
    String studentData=intent.getExtras().getString("student");


    context.startService(new Intent(context,MyIntentService.class));
}
}

0 个答案:

没有答案