我正在开发一个应用程序,当它打开时会收到收件箱和 Facebook 通知。我可以使用警报管理器每分钟在我的 android 应用程序中从 Facebook 获取收件箱和通知消息。但这会消耗大量智能手机的电池。有没有办法实时获取通知和收件箱,所以不必每分钟都请求?
这是我的代码:
MainFragment 类
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);
}
}
换句话说,我的问题是:有没有办法继续收听收件箱和通知并自动获取新消息而不是每分钟都请求?