在Android中通知用户新推文

时间:2013-01-24 20:48:17

标签: android twitter notifications

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

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

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

2 个答案:

答案 0 :(得分:1)

您可以检查的一种方法是轮询,但实际上并不建议这样做。您还可以使用一些pub-sub机制实现自己的服务器。

但是说,Twitter认识到这个用例并提供Streaming APIs。这将是实现您所谈论的最佳方式。

答案 1 :(得分: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){

        }

    }
}