问题
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