简体   繁体   中英

How to get real time inbox and notifications from Facebook SDK android

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?

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();
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM