1

I am developing an application that when it opens it get inbox and facebook notifications. I am able to get inbox and notification messages from Facebook in my android application every minute using Alarm Manager. But this consumes a lot of battery of the smartphone. Is there a way to get notifications and inbox in real time so It doesn't have to be requesting every minute?

This is my code:

MainFragment class

public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private Activity context;
private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};
private UiLifecycleHelper uiHelper;
private TextView InboxMessage,NotificationMessage,text1,text2;
private LoginButton authButton;

PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_login, container, false);
    authButton = (LoginButton) view.findViewById(R.id.authButton);
    authButton.setFragment(this);
    authButton.setPublishPermissions(Arrays.asList("manage_notifications"));
    InboxMessage= (TextView) view.findViewById(R.id.InboxTextView);
    NotificationMessage= (TextView) view.findViewById(R.id.NotificationsMessageTextView);
    text1= (TextView) view.findViewById(R.id.textView1);
    text2= (TextView) view.findViewById(R.id.textView2);
    context=this.getActivity();
    onClickNotifications();
    return view;
}
private void onSessionStateChange(final Session session, final SessionState state, final Exception exception) {
    if (state.isOpened()) {
        final Calendar TIME = Calendar.getInstance();
        am.setRepeating(AlarmManager.RTC,TIME.getTime().getTime(), 1000*60, pi);        
    } else {
        Log.i(TAG, "Logged out...");
        text1.setVisibility(View.INVISIBLE);
        InboxMessage.setVisibility(View.INVISIBLE);
        NotificationMessage.setVisibility(View.INVISIBLE);
        text2.setVisibility(View.INVISIBLE);
    }
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(getActivity(), callback);
    uiHelper.onCreate(savedInstanceState);
}
@Override
public void onResume() {
    super.onResume();
    uiHelper.onResume();
    Session session = Session.getActiveSession();
    if (session != null &&
           (session.isOpened() || session.isClosed()) ) {
        onSessionStateChange(session, session.getState(), null);
    }
    uiHelper.onResume();
}
public void onClickNotifications(){
    br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent i) {

            final Session session =Session.getActiveSession();
            if(session.isOpened()){  
                String aaa=new String();
                aaa="SELECT title_text,updated_time FROM notification WHERE recipient_id=me() AND is_unread=1";
                Bundle params = new Bundle();
                params.putString("q", aaa);
                     new Request(session,"/fql",params,HttpMethod.GET,new Request.Callback() {
                                 public void onCompleted(Response response) {
                                     try
                                     {
                                        GraphObject go  = response.getGraphObject();
                                        JSONObject  jso = go.getInnerJSONObject();
                                        JSONArray   arr = jso.getJSONArray( "data" );
                                        String splitting=arr.toString().replaceAll("\\\\|\\{|\\}|\\[|\\]", "");
                                        String[] arrayresponse=splitting.split("\\,");
                                        String s = "";
                                        for (int i = 0; i < arrayresponse.length; i++) {
                                            if (arrayresponse[i].length()>13){
                                                if (arrayresponse[i].substring(1,13).equals("updated_time"))
                                                    s+="* "+getDate(Long.valueOf(arrayresponse[i].substring(15,arrayresponse[i].length())))+"\n";
                                                else
                                                    s+="   "+arrayresponse[i].substring(14,arrayresponse[i].length()-1)+"\n\n";                                         
                                            }
                                        }
                                        text2.setVisibility(View.VISIBLE);
                                        NotificationMessage.setVisibility(View.VISIBLE);
                                        NotificationMessage.setMovementMethod(new ScrollingMovementMethod());
                                        NotificationMessage.setText(s);
                                        readMailBox(session);

                                     }catch ( Throwable t )
                                     {
                                         t.printStackTrace();
                                     }          
                                 }
                             }  
                     ).executeAsync();
            }
             else{
                 NotificationMessage.setVisibility(View.INVISIBLE);
                 Log.i(TAG, "Logged out...");
             }
     }
  };
    this.getActivity().registerReceiver(br, new IntentFilter("com.authorwjf.wakeywakey") );
    pi = PendingIntent.getBroadcast( this.getActivity(), 0, new Intent("com.authorwjf.wakeywakey"), 0 );
    am = (AlarmManager)(this.getActivity().getSystemService( Context.ALARM_SERVICE ));
}

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    time=time*1000;
    cal.setTimeInMillis(time);
    return DateFormat.format("dd-MM-yyyy hh:mm:ss aa", cal).toString();
}
public void readMailBox(Session session){
    String aaa=new String();
    aaa="SELECT timestamp,sender,body FROM unified_message where thread_id in (select thread_id from unified_thread  where folder = 'inbox') and unread=1";
    Bundle params = new Bundle();
    params.putString("q", aaa);
         new Request(session,"/fql",params,HttpMethod.GET,new Request.Callback() {
                     public void onCompleted(Response response) {
                         try
                         {
                            GraphObject go  = response.getGraphObject();
                            JSONObject  jso = go.getInnerJSONObject();
                            JSONArray   arr = jso.getJSONArray( "data" );
                            String splitting=arr.toString().replaceAll("\\\\|\\{|\\}|\\[|\\]", "");
                            String[] arrayresponse=splitting.split("\\,");
                            String s = "";                      
                                for (int i = 0; i < arrayresponse.length; i++) {
                                    if (arrayresponse[i].length()>10){
                                        if (arrayresponse[i].substring(1,10).equals("timestamp"))
                                            s+=getDate(Long.valueOf(arrayresponse[i].substring(13,arrayresponse[i].length()-4)))+"\n";
                                        else if (arrayresponse[i].substring(1,5).equals("name"))
                                            s+="* "+arrayresponse[i].substring(8,arrayresponse[i].length()-1)+"\n";
                                        else if (arrayresponse[i].substring(1,5).equals("body"))
                                            s+=arrayresponse[i].substring(7,arrayresponse[i].length())+"\n\n";
                                    }
                            }
                             text1.setVisibility(View.VISIBLE);
                             InboxMessage.setVisibility(View.VISIBLE);
                             InboxMessage.setMovementMethod(new ScrollingMovementMethod());
                             InboxMessage.setText(s);

                         }catch ( Throwable t )
                         {
                             t.printStackTrace();
                         }
                     }
                 }  
         ).executeAsync();

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {        
    uiHelper.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
    Session session =Session.getActiveSession();
    List<String> permissions = session.getPermissions();
     if (!permissions.contains("read_mailbox")) {

         Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(context, Arrays.asList("read_mailbox"));
         session.requestNewReadPermissions(newPermissionsRequest);
         readMailBox(session);
     } else {
         readMailBox(session);
     }
}

@Override
public void onPause() {
    super.onPause();
    uiHelper.onPause();
}

@Override
public void onDestroy() {      
    uiHelper.onDestroy();
    am.cancel(pi);
    this.getActivity().unregisterReceiver(br);
    super.onDestroy();
}


@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
}
}

In another words my question is: Is there a way to keep listening to inbox and notifications and automatically get new messages instead of requesting every minute?

Dany19
  • 551
  • 9
  • 26

1 Answers1

1

The best and perhaps the latest way of fetching notifications is to use FQL Facebook Query Language) and for your AGAIN WITHOUT OPENING APP part. You have to write your notification method in a service and the update it using some timer.I used Alarm Manager for that case.so that once you attain permission from the user to view his noifications, you can then continously fetch them in the background using the service. here is my method that I used to fetch notifications and then there conversion into json aswell.

 public void onClickNotifications(){



           Session session =Session.getActiveSession();

            if(session.isOpened()){  


                // session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));

                  String aaa=new String();
                    aaa="SELECT title_text FROM notification WHERE recipient_id=me() AND is_unread=1";

                    Bundle params = new Bundle();
                    params.putString("q", aaa);




                new Request(
                        session,
                        "/fql",
                        params,
                        HttpMethod.GET,
                        new Request.Callback() {
                            public void onCompleted(Response response) {



                 try
                        {
                            GraphObject go  = response.getGraphObject();
                            JSONObject  jso = go.getInnerJSONObject();
                            JSONArray   arr = jso.getJSONArray( "data" );

                            for ( int i = 0; i <  arr.length() ; i++ )
                            {

                                JSONObject json_obj = arr.getJSONObject( i );




                            adv.add(json_obj.getString( "title_text" ));


                            }
                        }
                        catch ( Throwable t )
                        {
                            t.printStackTrace();
                        }


                            }


                        }  
            ).executeAsync();

    }
            else{
                Toast.makeText(getApplicationContext(), "You are not logged in", Toast.LENGTH_LONG).show();
            }
    }
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Nauman Aslam
  • 299
  • 3
  • 14
  • 1
    the permission string that you have to use from your activity will be session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, "manage_notifications")); you are wellcome for any further queries aswell.Remember that this permission string will not work in service and hence you have to take permission once from the activity only – Nauman Aslam Jul 25 '14 at 12:38
  • Great, thanks a lot @NaumanAslam . excuse me , how can I get the unread inbox? I tried with this query but its not working: `SELECT message FROM mailbox_folder WHERE recipient_id=me() AND is_unread=1";` – Dany19 Jul 25 '14 at 21:02
  • 1
    Your welcome.Well if you want to get the total number of unread messages then this query "SELECT unread_count FROM mailbox_folder WHERE folder_id = 0 and viewer_id = me()" with the "read_mailbox" permission while if you want the body or the text of the message then you have to use unifies_message after getting the thread id.see this https://developers.facebook.com/docs/reference/fql/unified_message/ – Nauman Aslam Jul 27 '14 at 15:49
  • 1
    Well handing over complete codes would probably be against the rules of the website. You are suppose to try things out and then ask for the troubles you face. I can hand over you the code to repeat the alarm after regular intervals and for the service part do post the errors you face with the logcat and the world is full of nice and helping people. – Nauman Aslam Jul 30 '14 at 18:23
  • 1
    final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); final Calendar TIME = Calendar.getInstance(); Intent iserv = new Intent(context,fbService.class); PendingIntent pintent = PendingIntent.getService(context, 0, iserv, 0); m.setRepeating(AlarmManager.RTC,TIME.getTime().getTime(), 1000*600, pintent); – Nauman Aslam Jul 30 '14 at 18:23
  • this alarm manager once called then it will keep on calling the intent in it after every 10minutes (1000*600) Im simply calling my service class in it and this alarm manager is set in the onUpdate method of my widget so that it definatly is called when the app runs for the first time. – Nauman Aslam Jul 30 '14 at 18:25
  • thanks a lot .Now my code is working. excuse me do you know how to get the body and the sender of all unread inbox . I have tried with the following query: `SELECT sender,body FROM unified_message where thread_id in (select thread_id from unified_thread where folder = 'inbox') and unread=1"` but I only get message from one user and not all unread message. – Dany19 Jul 30 '14 at 20:31