android代码,用于检测我的android应用程序用户是否在线

android代码,用于检测我的android应用程序用户是否在线,android,Android,我已经开发了一个android应用程序,并在google play上发布了它。它已经被很多人下载(大约200-300)。现在我的问题是我想知道我的用户是否在线。实际上,当用户联机时,我希望在服务器中为该用户执行特定操作。我如何知道用户在线且当前正在查看我的应用程序屏幕 我试过下面的代码,它只能说明设备是否连接了互联网 private boolean isOnline() { try { ConnectivityManager cm

我已经开发了一个android应用程序,并在google play上发布了它。它已经被很多人下载(大约200-300)。现在我的问题是我想知道我的用户是否在线。实际上,当用户联机时,我希望在服务器中为该用户执行特定操作。我如何知道用户在线且当前正在查看我的应用程序屏幕

我试过下面的代码,它只能说明设备是否连接了互联网

private boolean isOnline()
    {
        try
        {
            ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo().isConnectedOrConnecting(); 
        }
        catch (Exception e)
        {
            return false;
        }
    }

我如何知道我的用户现在是否正在查看我的应用程序屏幕?我希望这将是一个可用的选项

尝试在
onResume
onPause
方法中添加一些代码

@Override
public void onResume() {
    super.onResume();
    isOnline(true);
    }
}


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

实现如下广播接收器类,该类将在互联网联机时发送广播:

public class InternetReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        boolean isConnected = new ConnectionDetector(context)
                .isConnectedToInternet();
        if (isConnected) {
            //user is connected 
        }
    }

public boolean isConnectedToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}
公共类InternetReceiver扩展了BroadcastReceiver{
@凌驾
公共void onReceive(上下文、意图){
布尔值isConnected=新连接检测器(上下文)
.isconnectedpointernet();
如果(未连接){
//用户已连接
}
}
公共布尔值isconnectedPointerNet(){
ConnectivityManager connectivity=(ConnectivityManager)context.getSystemService(context.connectivity\u SERVICE);
if(连接性!=null)
{
NetworkInfo[]info=connectivity.getAllNetworkInfo();
如果(信息!=null)
对于(int i=0;i
在清单中,定义为:

<receiver android:name="com.example.InternetReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>


因此,当用户进入应用程序并连接互联网时,您可以这样做,只需在您的在线数据库的onResume()中将用户状态更新为“Online”,当用户退出应用程序时,将状态更新为“offline”。实际上,这个实现包括前端和后端代码。你的问题范围很大。嗨,chintan,请查看我对avinash Answer的评论。你想在你的服务器上还是在Android设备上检查?在服务器上会很好,但我的应用程序中有很多活动类。我应该把这个代码放在哪个类中?(根据用户类型,我有不同类型的用户登录屏幕和相应的活动)@KPRanjith通常在用户停留时间较长的主要活动中使用这种代码。把它放在其他活动中也没什么坏处好的,阿维纳什谢谢你的回复让我试试这个。。让你知道:)嗨,克莱尔,请检查我对阿维纳什答案的评论,我会试试这个,让你知道结果。