[JNI] Sending a android.content.Context parameter to a function

I am trying to create a method that checks for internet connection that needs a Context parameter. The JNIHelper allows me to call static functions with parameters, but I don’t know how to “retrieve” Cocos2d-x Activity class to use it as a parameter.

@
public static boolean isNetworkAvailable(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase(“WIFI”))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase(“MOBILE”))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
@

and the c++ code is

@
JniMethodInfo methodInfo;
if ( !JniHelper::getStaticMethodInfo( methodInfo,
“my/app/TestApp”, “isNetworkAvailable”, “(android/content/Context;)V”))
{
//error
return;
}
CCLog( “Method found and loaded!”);
methodInfo.env~~>CallStaticVoidMethod;
methodInfo.env~~>DeleteLocalRef( methodInfo.classID);
@

It is probably much easier to store your Application or Activity instance somewhere in your Java code (e.g. in the activities onCreate()).
Then use something like Cocos2dActivity.sharedInstance().getContext() within your isNetworkAvailable() function.

I have modified it, but I am not sure of its behaviour. I wanted some class that would be plug&play for c++ without modifying the cocos2dx generated java classes.

@
public class InternetConnection{
static private Activity m_kActivity = null;

public InternetConnection( Activity activity) {
super();

m_kActivity = activity;
}

public static boolean isNetworkAvailable() {
if (connectionType() > 0)
return true;
else
return false;
}
@

You could simply subclass the Cocos2dActivity, so you have a plug&play activity class for upcoming projects.

public class MyActivity extends Cocos2dActivity {
  private static Activity instance;

  public void onCreate() {
    super();
    instance = this;
  }

  public static Activity getInstance() {
    return instance;
  }
}

And within your isNetworkAvailable() method do the following:

public static boolean isNetworkAvailable() {
  Context context = MyActivity.getInstance();
  [...] // same code as your first post
}

Don’t forget to declare your new MyActivity class as the main activity within your AndroidManifest.xml