cocos2d项目获取手机网络以及设置手机震动

时间:2023-02-08 00:19:46

                                            cocos2d项目获取手机网络以及设置手机震动

获取网络状态

首先说明一下流程,c++通过jni调用java方法获取网络状态。

 

获取网络方法:

/*添加获取当前网络状态方法 (返回参数说明:netType-1:没有网络,1wifi,2:手机网络。

netLevel1: None 2:poor  3:moderate  4:good  5:great )*/

void HelloWorld::getNetInfo(int &netType, int &netLevel)

{

#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

JniMethodInfo minfo;

bool isHave = JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity", "getNetInfo", "()[I");

if (isHave)

{

jintArray msg = (jintArray)minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);

int len = minfo.env->GetArrayLength(msg);

jint* elems = minfo.env->GetIntArrayElements(msg, 0);

if (2 == len)

{

netType = elems[0];

netLevel = elems[1];

}

log(" c ++ netType :%d----------netLevel: %d ----------- %d", netType, netLevel, len);

 

minfo.env->ReleaseIntArrayElements(msg, elems, 0);

minfo.env->DeleteLocalRef(minfo.classID);

}

else

{

cocos2d::log("JniFun call getNetInfo error!");

}

#endif

#if(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

IOSCommonFunc::GetInstance().getNetState(netType, netLevel);

#endif

}

 

手机震动方法:

//手机震动

void HelloWorld::PhoneShake()

{

#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

JniMethodInfo minfo;

bool isHave = JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity", "PhoneShake", "()V");

if (!isHave)

{

log("PhoneShake Function In Java Is Null!");

}

else

{

minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID);

minfo.env->DeleteLocalRef(minfo.classID);

}

#endif

 

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

IOSPlatform::GetInstance().PhoneShake();

#endif

}

 

对应的java里的方法,在org/cocos2dx/cpp/AppActivity文件中。

/********************************************************************

package org.cocos2dx.cpp;

 

import java.util.ArrayList;

 

import org.cocos2dx.lib.Cocos2dxActivity;

import android.app.Activity;

import android.app.AlertDialog;

import android.app.Service;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.pm.ActivityInfo;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.net.wifi.WifiInfo;

import android.net.wifi.WifiManager;

import android.os.Bundle;

import android.os.Vibrator;

import android.provider.Settings;

import android.telephony.PhoneStateListener;

import android.telephony.SignalStrength;

import android.telephony.TelephonyManager;

import android.util.Log;

import android.view.WindowManager;

 

public class AppActivity extends Cocos2dxActivity {

private static AppActivity instance;

//添加获取网络状态方法--------------------------begin

   //网络状态强度

    public static final int NETLEVEL_STRENGTH_NONE_OR_UNKNOWN = 0;

public static final int NETLEVEL_STRENGTH_POOR = 1;

public static final int NETLEVEL_STRENGTH_MODERATE = 2;

public static final int NETLEVEL_STRENGTH_GOOD = 3;

public static final int NETLEVEL_STRENGTH_GREAT = 4;

private static native boolean nativeIsLandScape();

    private static native boolean nativeIsDebug();

//信号监听

TelephonyManager        Tel;  

MyPhoneStateListener    MyListener;

public static int singnalLevel;

//Wifi监听

private static WifiInfo wifiInfo = null;

private static WifiManager wifiManager = null;

public static int wifiLevel;

static String hostIPAdress = "0.0.0.0";

//添加获取网络状态方法--------------------------end

 @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        

        

        //GCloudVoiceEngine.getInstance().init(getApplicationContext(), this);

        

        instance = this;

        

        Log.d("onCreate", "onCreate"+Context.TELEPHONY_SERVICE);

        

        if(true) {

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

        } else {

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

        }

        //2.Set the format of window

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // Check the wifi is opened when the native is debug.

        if(false)

        {

            if(!isNetworkConnected())

            {

                AlertDialog.Builder builder=new AlertDialog.Builder(this);

                builder.setTitle("Warning");

                builder.setMessage("Please open WIFI for debuging...");

                builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {

                    

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

                        finish();

                        System.exit(0);

                    }

                });

 

                builder.setNegativeButton("Cancel", null);

                builder.setCancelable(true);

                builder.show();

            }

            hostIPAdress = getHostIpAddress();

        }

        //添加获取网络状态方法--------------------------begin        

        //添加信号强度监听

        MyListener = new MyPhoneStateListener();

        Tel = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

        Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

 

        //添加wifi强度监听

        wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);

// //添加获取网络状态方法--------------------------end

        

        

    }

 

 private boolean isNetworkConnected() {

         ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  

         if (cm != null) {  

             NetworkInfo networkInfo = cm.getActiveNetworkInfo();  

         ArrayList networkTypes = new ArrayList();

         networkTypes.add(ConnectivityManager.TYPE_WIFI);

         try {

             networkTypes.add(ConnectivityManager.class.getDeclaredField("TYPE_ETHERNET").getInt(null));

         } catch (NoSuchFieldException nsfe) {

         }

         catch (IllegalAccessException iae) {

             throw new RuntimeException(iae);

         }

         if (networkInfo != null && networkTypes.contains(networkInfo.getType())) {

                 return true;  

             }  

         }  

         return false;  

     }

 

 public String getHostIpAddress() {

        WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);

        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        int ip = wifiInfo.getIpAddress();

        return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));

    }

//--------------------------------------网络类型及强度  begin------------------------------------------

    //保存返回的数组

    static int[] netInfo = new int[2];

 

    //netType   -1: 没有网络    1: WIFI     2: 移动数据

    //netLevel  1: None 2:poor  3:moderate  4:good  5:great

    public static int[] getNetInfo() {

Log.d("getNetInfo", "enter the function getNetInfo ----- ");

        ConnectivityManager connMgr = (ConnectivityManager)instance.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null == connMgr) return netInfo;

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if( null == networkInfo)

            return netInfo;

        int nType = networkInfo.getType();

        if (nType == ConnectivityManager.TYPE_MOBILE) {

            netInfo[0] = 2;

        }

        else if (nType == ConnectivityManager.TYPE_WIFI) {

            netInfo[0] = 1;

        }

        Log.d("getNetInfo", "java ---- netType --- "+ netInfo[0]);

 

        //according to netType. set the value of netLevel

        switch (netInfo[0]) {

        case 1:

            netInfo[1] = getWifiLevel();

            break;

        case 2:

            netInfo[1] = getSingnalLevel();

            break;

        default:

            break;

        }

        Log.d("getNetInfo", "java ---- netLevel --- "+ netInfo[1]);

 

        return netInfo;

    }

    //信号强度等级

    private class MyPhoneStateListener extends PhoneStateListener  

    {  

      @Override  

      public void onSignalStrengthsChanged(SignalStrength signalStrength)  

      {  

         super.onSignalStrengthsChanged(signalStrength);  

         Tel = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

         int networkType = Tel.getNetworkType();

         

        /* int asu = signalStrength.getGsmSignalStrength();

         if (asu <= 2 || asu == 99) singnalLevel = NETLEVEL_STRENGTH_NONE_OR_UNKNOWN;

         else if (asu >= 12) singnalLevel = NETLEVEL_STRENGTH_GREAT;

         else if (asu >= 8)  singnalLevel = NETLEVEL_STRENGTH_GOOD;

         else if (asu >= 5)  singnalLevel = NETLEVEL_STRENGTH_MODERATE;

         else singnalLevel = NETLEVEL_STRENGTH_POOR;

         Log.d("getNetInfo", "asu==" + asu);*/

 

         switch (networkType) {

         case TelephonyManager.NETWORK_TYPE_GPRS:

         case TelephonyManager.NETWORK_TYPE_EDGE:

         case TelephonyManager.NETWORK_TYPE_CDMA:

         case TelephonyManager.NETWORK_TYPE_1xRTT:

         case TelephonyManager.NETWORK_TYPE_IDEN:

          singnalLevel = 2;

             break;

         case TelephonyManager.NETWORK_TYPE_UMTS:

         case TelephonyManager.NETWORK_TYPE_EVDO_0:

         case TelephonyManager.NETWORK_TYPE_EVDO_A:

         case TelephonyManager.NETWORK_TYPE_HSDPA:

         case TelephonyManager.NETWORK_TYPE_HSUPA:

         case TelephonyManager.NETWORK_TYPE_HSPA:

         case TelephonyManager.NETWORK_TYPE_EVDO_B:

         case TelephonyManager.NETWORK_TYPE_EHRPD:

         case TelephonyManager.NETWORK_TYPE_HSPAP:

          singnalLevel = 3;

             break;

         case TelephonyManager.NETWORK_TYPE_LTE:

          singnalLevel = 4;

             break;

         case TelephonyManager.NETWORK_TYPE_UNKNOWN:

          singnalLevel = 0;

         default:

             singnalLevel = 2;

             break;

     }

         

      }  

    };/* End of private Class */  

    //获取信号强度

    public static int getSingnalLevel() {

         return singnalLevel;

    }

 

    //获取wifi强度

    public static int getWifiLevel() {

     Log.d("getWifiLevel", "getWifiLevel");

        wifiInfo = wifiManager.getConnectionInfo();

        int wifiStrength = wifiInfo.getRssi();

        if (wifiStrength <= 0 && wifiStrength >= -50) {  

            wifiLevel = NETLEVEL_STRENGTH_GREAT;

        } else if (wifiStrength < -50 && wifiStrength >= -70) {  

            wifiLevel = NETLEVEL_STRENGTH_GOOD;

        } else if (wifiStrength < -70 && wifiStrength >= -80) {  

            wifiLevel = NETLEVEL_STRENGTH_MODERATE;

        } else if (wifiStrength < -80 && wifiStrength >= -100) {  

            wifiLevel = NETLEVEL_STRENGTH_POOR;

        } else {  

            wifiLevel = NETLEVEL_STRENGTH_NONE_OR_UNKNOWN;

        }

        return wifiLevel;

    }

//--------------------------------------网络类型及强度  end------------------------------------------

  //手机震动

   public static void PhoneShake(){

   Log.d("PhoneShake", "PhoneShake-----------------------");

   Vibrate(instance, 1000); //1000毫秒

   }

   public static void Vibrate(final Activity activity, long milliseconds) {

Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);

vib.vibrate(milliseconds);

}

}

 

这样的话方法都有了,但是还需要在清单文件AndroidManifest.xml中添加一些权限,先添加

<intent-filter>

              <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

 

             <category android:name="android.intent.category.DEFAULT" />

         </intent-filter>

 

 

再添加权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  <uses-permission android:name="android.permission.INTERNET" />

  <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

  <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

  <uses-permission android:name="android.permission.WAKE_LOCK"/>

  <uses-permission android:name="android.permission.RECORD_AUDIO" />

  <uses-permission android:name="android.permission.VIBRATE" />

  <uses-permission android:name="android.permission.BLUETOOTH" />

  <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

 

如果你的项目libs中没有android-support-v4.jar的话,你还需要加一个android-support-v4.jar包,然后就可以编译打包了。

 

我调用之后打包

int sNetType = -1;

int sNetLevel = 0;

this->getNetInfo(sNetType, sNetLevel);

CCString* ns = CCString::createWithFormat("%d", (sNetType * 10 + sNetLevel));

number->setString(ns->_string);

this->PhoneShake();

 

我打包出来之后获取到的网络类型是1,4无线网good

cocos2d项目获取手机网络以及设置手机震动