0

我正在制作聊天应用程序(仅供趣味)。我使用Pushy API在两个用户之间发送消息。按照pushy.me网站上提供的教程,Push消息在广播接收器中接收。好吧,这部分工作正常,但现在我正在制作一个类似Whats App的通知系统,当用户不在聊天中时,它会启动通知栏。仅当片段可见时才发送通知

我的想法如下:如果聊天片段可见,只需使用LocalBroadcastManager sendBroadcast方法更新片段,否则启动通知。

我'使该与sucess用下面的代码:

if (!Utility.isAppInBg(context)) { 
       Intent chatPushNotification = new Intent(Constants.CHAT_PUSH_NOTIFICATION); 
       chatPushNotification.putExtra("chat", obj.toString()); 
       LocalBroadcastManager.getInstance(context).sendBroadcast(chatPushNotification); 
      } else { 
       if (title != null && msg != null) { 

        NotificationUtil.notify(context, NOTIFICATION_ID, notifyIntent, 
          URLDecoder.decode(title, "UTF-8"), URLDecoder.decode(msg, "UTF-8")); 
       } 
      } 

的问题是,该方法使用isAppInBg与ActivityManager getRunningAppProcesses()方法,这是气馁。有另一种方法可以替代另一种方法来检查片段是否可见(请记住,此检查是在广播接收器中进行的)?如果没有,有更好的方法?

回答

0

这种方法对我来说工作得很好。

public class MyActivity extends Activity { 

static boolean active = false; 

@Override 
public void onStart() { 
    super.onStart(); 
    active = true; 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    active = false; 
} 

@Override 
public void onPause() { 
    super.onPause(); 
    active = false; 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    active = true; 

} 

和接收器

if(!MyActivity.active){ 
    //alert notification 
} 
else{ 
    //send broadcast 
} 
+0

哇,这么简单干净!奇迹般有效!谢谢! –

相关问题