joe

cocos creater 获取IMEI和设备id

cocos creater 没有带获取手机IEMI和设备id的接口,只能自己获取,需要修改原生的安卓代码才能获取。


可以参考官方文档:https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html


获取IEMI需要开启权限获取设备id无需权限,所以建议获取设备id


首先构建项目,构建出安卓代码。

找到安卓代码里面的位置,我的文件地址是(\项目地址\build\jsb-link\frameworks\runtime-src\proj.android-studio\app\src\org\cocos2dx\javascript)


我这里是获取设备id的,无需开启权限,


获取设备id

修改AppActivity.java代码:

/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;

import android.content.Intent;
import android.content.res.Configuration;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;

import java.lang.reflect.Method;

public class AppActivity extends Cocos2dxActivity {

    public static String imei="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            //  so just quietly finish and go away, dropping the user back into the activity
            //  at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return;
        }
        // DO OTHER INITIALIZATION BELOW
        SDKWrapper.getInstance().init(this);

        imei = getIMEI(this);
    }
    
    /**
     * 映射返回获取imei
     * @param context
     * @return
     */
    public static String getIMEI2(String title, String message) {
        return  imei;
    }


    /**
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        //获取设备的id
        return  Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        
        //获取IMEI,需要开启权限
//         TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
////        TelephonyManager manager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
//        try {
//            Method method = manager.getClass().getMethod("getImei", int.class);
//            String imei1 = (String) method.invoke(manager, 0);
//            String imei2 = (String) method.invoke(manager, 1);
//            if(TextUtils.isEmpty(imei2)){
//                return imei1;
//            }
//            if(!TextUtils.isEmpty(imei1)){
//                //因为手机卡插在不同位置,获取到的imei1和imei2值会交换,所以取它们的最小值,保证拿到的imei都是同一个
//                String imei = "";
//                if(imei1.compareTo(imei2) <= 0){
//                    imei = imei1;
//                }else{
//                    imei = imei2;
//                }
//                return imei;
//            }
//        } catch (Exception e) {
////            e.printStackTrace();
//            try {
//                if (manager.getDeviceId() != null) {
//                    return manager.getDeviceId().toString();
//                } else {
//                    return Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
//                }
//            } catch (Exception e2) {
//                return Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
//            }
//        }
//        return "";
    }





    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
        SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);

        return glSurfaceView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SDKWrapper.getInstance().onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        SDKWrapper.getInstance().onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKWrapper.getInstance().onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        SDKWrapper.getInstance().onNewIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SDKWrapper.getInstance().onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        SDKWrapper.getInstance().onStop();
    }
        
    @Override
    public void onBackPressed() {
        SDKWrapper.getInstance().onBackPressed();
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        SDKWrapper.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        SDKWrapper.getInstance().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        SDKWrapper.getInstance().onStart();
        super.onStart();
    }
}


然后在cocos creater代码里面直接调用:

 //rtn 就是设备id,传参自己按照官方文档修改就行,,可以自己加标识
 var rtn = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getIMEI2", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", "title", "message");


如果需要获取IMEI

首先,添加安卓权限,我的项目地址:\项目地址\build\jsb-link\frameworks\runtime-src\proj.android-studio\app

找到AndroidManifest.xml 文件,添加权限

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

然后把获取imei函数注释修改一下,

    /**
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        // return  Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//        TelephonyManager manager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
       try {
           Method method = manager.getClass().getMethod("getImei", int.class);
           String imei1 = (String) method.invoke(manager, 0);
           String imei2 = (String) method.invoke(manager, 1);
           if(TextUtils.isEmpty(imei2)){
               return imei1;
           }
           if(!TextUtils.isEmpty(imei1)){
               //因为手机卡插在不同位置,获取到的imei1和imei2值会交换,所以取它们的最小值,保证拿到的imei都是同一个
               String imei = "";
               if(imei1.compareTo(imei2) <= 0){
                   imei = imei1;
               }else{
                   imei = imei2;
               }
               return imei;
           }
       } catch (Exception e) {
//            e.printStackTrace();
           try {
               if (manager.getDeviceId() != null) {
                   return manager.getDeviceId().toString();
               } else {
                   return Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
               }
           } catch (Exception e2) {
               return Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
           }
       }
       return "";
    }


注意:为了防止没有授权app闪退,所以没授权 就获取设备id,所以一开始没有授权后面授权了,获取的id就会不一样
码字很辛苦,转载请注明来自朱一兵的博客《cocos creater 获取IMEI和设备id》

评论