2

我设计了一个应用程序来帮助玉米农民识别疾病和虫害问题,以更好地照顾他们的作物,我还集成了一个 Twitter 提要,让他们可以看到当地推广服务代理之一的最新推文。这些推文将让农民了解已报告或正在传播的任何当地虫害/疾病问题,以便农民做好准备,并希望在问题变得严重之前修复他们的作物。

我想知道的是如何让我的应用程序检查新推文并通知用户。我正在使用“http://api.twitter.com/1/statuses/user_timeline.json”来获取推文,所以我不相信推送通知会起作用。这是可能的,还是有另一种方法来检查和通知用户?

tl;dr:我的应用程序如何通知用户新的推文?

4

2 回答 2

1

您可以检查的一种方法是轮询,但实际上并不推荐这样做。您还可以使用一些发布-订阅机制实现您自己的服务器。

但话虽如此,Twitter 认识到了这个用例并提供了Streaming API。这将是实现您正在谈论的内容的最佳方式。

于 2013-01-24T22:06:42.837 回答
0

你可以试试下面的代码。可能包含一些语法错误。

public class TwitterUpdater {
     Context context;
     public TwitterUpdate(Context ctx){
        context = ctx;
        Timer timer = new Timer;
        timer.scheduleAtFixedRate(new TwitterTask(), 0, 300000);
     }

}

public class TwitterTask extends TimerTask{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        this.loadMessages();
    }

}
public void loadMessages(){
        StringBuilder builder = new StringBuilder();
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

           DefaultHttpClient client = new DefaultHttpClient();

           SchemeRegistry registry = new SchemeRegistry();
           SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
           socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
           registry.register(new Scheme("https", socketFactory, 443));
           SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
           DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

           // Set verifier      
           HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);


        HttpGet httpGet = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=<Your twitter account name>");
        try {
          HttpResponse response = httpClient.execute(httpGet);
          StatusLine statusLine = response.getStatusLine();
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
            JSONArray obj = new JSONArray(builder.toString());
            if (obj.getClass() == JSONArray.class){
                JSONArray  results = obj;
                for(int i = 0; i < results.length(); i++){
                    JSONObject result = results.getJSONObject(i);

                    JSONObject user = result.getJSONObject("user");
                    if(((String) user.get("screen_name")).compareToIgnoreCase("TNCVB")== 0){
                        String name = user.getString("screen_name");
                        String text =result.getString("text");
                        String timestamp = result.getString("created_at");
                        //Put them in an object and add to array or something
                    }
                }
            }

                Intent nintent = new Intent(context, MyActivity.class);
                PendingIntent pintent = PendingIntent.getActivity(context, 0, nintent, 0);

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("Update")
                        .setContentIntent(pintent)
                        .setContentText("New messages are available.");
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(007, mBuilder.build());
          } else {
            Log.e("JSON Error:", "Failed to download file");
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }catch(Exception e){

        }

    }
}
于 2013-01-24T22:35:26.957 回答