android code to detect whether my android app user is online or not

前提是你 提交于 2021-02-18 08:39:33

问题


I have developed a android application, have launched it in google play. It has been downloaded by many people (around 200-300) . Now my question is i want to know if my user is online or not. Actually i want to perform a particular action in my server for that user when the user is online. How can i know the user is online and currently viewing my app screen?

i have tried the below code , which can only say whether device has internet conncetion or not..

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

How can i know whether my user is viewing my app screen now? i hope there will be a option available for this!


回答1:


Try to have some code in onResume and onPause methods

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


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



回答2:


Implement Broadcast Receiver Class as follows which will send broadcast whenever internet is online:

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

In Manifest define as :

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


来源:https://stackoverflow.com/questions/29406264/android-code-to-detect-whether-my-android-app-user-is-online-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!