Get phone battery and contacts

                                                        Get phone battery and contacts

When we have some games, we need to obtain the information of the mobile phone, and sometimes we also obtain the user's address book permission. When I was bored, I studied it to see how to obtain it. After the study, I wrote it down. It may be useful to encounter it, after all, the brain is not good.

1. Get power

The C++ method is as follows:

// Add a method to get the current battery

void HelloWorld::GetBatteryLevel(int &batteryLevel)

{

 

#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID

JniMethodInfo minfo;

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

if (isHave)

{

jint battery = (jint)minfo.env->CallStaticIntMethod(minfo.classID, minfo.methodID);

log(" cocos2dx--currentBattery :%d----------", battery);

batteryLevel = battery;

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

}

else

{

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

}

#endif

#if(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

batteryLevel = IOSCommonFunc::GetInstance().getBatteryLeve();

#endif

}

 

Then add the following method in java :

//--------------------------------------Battery information begin------- -----------------------------------

    class BatteryBroadcastReceiver extends BroadcastReceiver{

 

        @Override

        publicvoidonReceive(Context context, Intent intent) {  

            // TODO Auto-generated method stub

            //Determine whether it is a Broadcast Action for battery changes

            if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){

                //Get the current battery

                int level = intent.getIntExtra("level", 0);

                //Total scale of electricity

                int scale = intent.getIntExtra("scale", 100);

                // convert it to percentage

                batteryLevel =  level * 100 / scale;

                Log.d("batteryLevel", "batteryLevel-----------------------"+batteryLevel);

            }

        }

 

    }

 

    //Get battery information

    publicstaticint getBatteryLevel() {  

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

    Log.d("getBatteryLevel", "java ---- netLevel --- "+ batteryLevel);

        returnbatteryLevel; 

    }

 

    //--------------------------------------Battery information end------- -----------------------------------

 

After adding, you will find an error because there are no variables and methods defined . Add the following variables in front of the file :

//Add the method to get power ----------------------------begin

BatteryBroadcastReceiver receiver = newBatteryBroadcastReceiver(); 

IntentFilter filter = newIntentFilter(Intent.ACTION_BATTERY_CHANGED); 

publicstaticintbatteryLevel = 0;   

//Add a method to get power ---------------------------- end

 

When you get here, you will find that there is no error, but you still can't get it after packaging, and an error will be reported. This is because the power information monitoring is not added , and the monitoring is added in onCreate .

 

//Add battery information monitoring

    registerReceiver(receiver, filter);

 

That's it, the battery information I get is 100 because my phone is always charging.

Let me explain here that the power information of this battery will respond every time there is a change in the monitor.

 

 

 

 

2. Get the address book

C++ method:

std::string HelloWorld::getContactPicker()

{

std::string ret("");

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

JniMethodInfo minfo;

 

bool isHave = JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity", "getContactPicker", "()Ljava/lang/String;");

 

if (!isHave)

{

log("jni StopBaiDuLocation is null");

}

else

{

jstring str = (jstring)minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);

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

ret = JniHelper :: jstring2string (str);

//std::cout<<ret<<end;

minfo.env->DeleteLocalRef(str);

}

 

#endif

 

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

ret = IOSPlatform::GetInstance().getContactPicker();

#endif

return ret;

}

 

The code in Java is as follows:

 

publicstatic String getContactPicker() throws JSONException{ 

        //Some particularly important permissions after Android 6.0 need to be applied for separately, instead of agreeing at the time of installation

          int currentVersion = android.os.Build.VERSION.SDK_INT;

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

          if (currentVersion >= 23)

          {

               if (ContextCompat.checkSelfPermission(instance, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)

               {        

               ActivityCompat.requestPermissions(instance, new String[]{Manifest.permission.READ_CONTACTS}, 0);//申请权限  

               }

               else 

               {

               //has the current permission  

               }  

          }

          ContentResolver resolver = instance.getContentResolver();

          String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};

          Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,cols, null, null, null);

          Log.d("getContactPicker", "enter the function getContactPicker -----111111111111-- "+cursor.getCount());

          JSONArray root = new JSONArray();

          for (int i = 0; i < cursor.getCount(); i++) {

 

              cursor.moveToPosition(i);

              int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);

              int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

              String name = cursor.getString(nameFieldColumnIndex);

              String number = cursor.getString(numberFieldColumnIndex);

 

              JSONObject onePerson = new JSONObject();

              onePerson.put("sPhoneName", name);

              onePerson.put("sPhoneNumber", number);

              

              Log.d("sPhoneName", "sPhoneName"+name);

              Log.d("sPhoneNumber", "sPhoneNumber"+number);

 

              root.put(onePerson);

 

          }

          JSONObject writeJson = new JSONObject();

          writeJson.put("info", root);

          return writeJson.toString();

      }

 

When you get here, you will find that you can't get the phone's address book, because the permissions are missing, add permissions to the manifest file:

<!--Permission to add contacts-->

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

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

 

After packing and testing, I saved Kobe and James' mobile phone numbers in my phone to see if I could get them.

My code is as follows:

std::string str;

str = this->getContactPicker();

number->setString(str);

 

turn out:

 

You can also see the result in the above screenshot. It should be noted that the final result obtained is a json . If necessary, it needs to be parsed, and the parsing steps will not be described here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324808786&siteId=291194637