- 对Device插件的Device.java文件进行修改
源码:
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.device;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String platform; // Device OS
public static String uuid; // Device UUID
private static final String ANDROID_PLATFORM = "Android";
private static final String AMAZON_PLATFORM = "amazon-fireos";
private static final String AMAZON_DEVICE = "Amazon";
/**
* Constructor.
*/
public Device() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Device.uuid = getUuid();
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("getDeviceInfo".equals(action)) {
JSONObject r = new JSONObject();
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", this.getPlatform());
r.put("model", this.getModel());
r.put("manufacturer", this.getManufacturer());
r.put("isVirtual", this.isVirtual());
r.put("serial", this.getSerialNumber());
r.put("imsi", this.getimsi());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Get the OS name.
*
* @return
*/
public String getPlatform() {
String platform;
if (isAmazonDevice()) {
platform = AMAZON_PLATFORM;
} else {
platform = ANDROID_PLATFORM;
}
return platform;
}
/**
* Get the device's Universally Unique Identifier (UUID).
*
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
public String getModel() {
String model = android.os.Build.MODEL;
return model;
}
public String getProductName() {
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getManufacturer() {
String manufacturer = android.os.Build.MANUFACTURER;
return manufacturer;
}
public String getSerialNumber() {
String serial = android.os.Build.SERIAL;
return serial;
}
/**
* Get the OS version.
*
* @return
*/
public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
/**
* Function to check if the device is manufactured by Amazon
*
* @return
*/
public boolean isAmazonDevice() {
if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) {
return true;
}
return false;
}
public boolean isVirtual() {
return android.os.Build.FINGERPRINT.contains("generic") ||
android.os.Build.PRODUCT.contains("sdk");
}
/**
* Get the imsi.
*
* @return
*/
public String getimsi() {
String imsiID = "";
try {
TelephonyManager systemService = (TelephonyManager) this.cordova.getActivity()
.getSystemService(Context.TELEPHONY_SERVICE);
if (systemService.getSubscriberId()) {
imsiID = systemService.getSubscriberId();
System.out.println("imsiID" + imsiID);
}
} catch (Exception e) {
}
return imsiID;
}
}
- 对device.js进行修改
源码:
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var argscheck = require('cordova/argscheck'),
channel = require('cordova/channel'),
utils = require('cordova/utils'),
exec = require('cordova/exec'),
cordova = require('cordova');
channel.createSticky('onCordovaInfoReady');
// Tell cordova channel to wait on the CordovaInfoReady event
channel.waitForInitialization('onCordovaInfoReady');
/**
* This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
* phone, etc.
* @constructor
*/
function Device() {
this.available = false;
this.platform = null;
this.version = null;
this.uuid = null;
this.cordova = null;
this.model = null;
this.manufacturer = null;
this.isVirtual = null;
this.serial = null;
this.imsi = null;//2019年7月12日13:59:43 添加获取手机唯一识别码
var me = this;
channel.onCordovaReady.subscribe(function() {
me.getInfo(function(info) {
//ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js
//TODO: CB-5105 native implementations should not return info.cordova
var buildLabel = cordova.version;
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.uuid = info.uuid;
me.cordova = buildLabel;
me.model = info.model;
me.isVirtual = info.isVirtual;
me.manufacturer = info.manufacturer || 'unknown';
me.serial = info.serial || 'unknown';
me.imsi = info.imsi;//2019年7月12日13:59:43 添加获取手机唯一识别码
channel.onCordovaInfoReady.fire();
},function(e) {
me.available = false;
utils.alert("[ERROR] Error initializing Cordova: " + e);
});
});
}
/**
* Get device info
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
*/
Device.prototype.getInfo = function(successCallback, errorCallback) {
argscheck.checkArgs('fF', 'Device.getInfo', arguments);
exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
};
module.exports = new Device();
android平台下的AndroidManifest.xml文件中添加
<permission android:name="android.permission.READ_PHONE_STATE" />
一般做完上面操作就可以获取到imsi,但部门版本权限请求会失败所以需要单独进行权限请求
在android平台下的
- 在plugin.xml文件中添加
-
<config-file target="AndroidManifest.xml" parent="/manifest">
<!-- Required 一些系统要求的权限,如访问网络等-->
<!-- 此处添加项目中所需的所有权限,没有可不添加-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</config-file>
-
MainActivity.java中做如下修改
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.km.KMmobileOa; import android.app.Activity; import android.app.AlarmManager; import android.app.Application; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.widget.Toast; import org.apache.cordova.*; public class MainActivity extends CordovaActivity { private static final int READ_PHONE_STATE = 1000; Application application; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // enable Cordova apps to be started in the background Bundle extras = getIntent().getExtras(); if (extras != null && extras.getBoolean("cdvStartInBackground", false)) { moveTaskToBack(true); } //判断是否为android6.0系统版本,如果是,需要动态添加权限 if (Build.VERSION.SDK_INT>=23){ showContacts(); } // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); } public void showContacts(){ if ( ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(),"没有权限,请手动开启读取手机信息权限",Toast.LENGTH_SHORT).show(); // 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义) ActivityCompat.requestPermissions(MainActivity.this,new String[]{ Manifest.permission.READ_PHONE_STATE}, READ_PHONE_STATE); } } //Android6.0申请权限的回调方法 @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { // requestCode即所声明的权限获取码,在checkSelfPermission时传入 case READ_PHONE_STATE: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // // 获取到权限,作相应处理 // Toast.makeText(this, "权限请求成功", Toast.LENGTH_SHORT).show(); // Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName()); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); // AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用 // Intent intent = new Intent(this, Object.class); // startActivity(intent); // System.exit(0); toinit(this); } else { // 没有获取到权限,做特殊处理 Toast.makeText(getApplicationContext(), "获取读取手机信息权限失败,请手动开启", Toast.LENGTH_SHORT).show(); } break; default: break; } } public static void toinit(Activity activity) { Intent intent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); activity.finish(); } }