針對安卓個別手機拿不到IMEI
package com.zzyuyou.demo;import android.Manifest;
import android.app.AlarmManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity2 extends AppCompatActivity {
private final int PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//<span style="background-color: rgb(255, 255, 255); color: rgb(33, 33, 33); font-family: inherit; white-space: pre-wrap;"><font size="2">先申請權限</font></span>
setPerssion();
}
private void initData() {
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
String szImei = TelephonyMgr.getDeviceId();
Toast.makeText(this, "::" + szImei, Toast.LENGTH_SHORT).show();
}
// <span style="background-color: rgb(255, 255, 255); color: rgb(33, 33, 33); font-family: inherit; white-space: pre-wrap;"><font size="2">申請權限</font></span>
private void setPerssion() {
// <font size="2"><span style="background-color: rgb(255, 255, 255); color: rgb(33, 33, 33); font-family: inherit; white-space: pre-wrap;">檢查有沒有權限</span> </font>READ_PHONE_STATE
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// <span style="background-color: rgb(255, 255, 255); color: rgb(33, 33, 33); font-family: inherit; white-space: pre-wrap;"><font size="2">沒有權限申請獲取</font></span>
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE},
PERMISSIONS_WRITE_EXTERNAL_STORAGE);
} else {
initData();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSIONS_WRITE_EXTERNAL_STORAGE) {
if (grantResults == PackageManager.PERMISSION_GRANTED) {
initData();
} else {
Toast.makeText(MainActivity2.this, "<span style="background-color: rgb(255, 255, 255); color: rgb(33, 33, 33); font-family: inherit; white-space: pre-wrap;"><font size="2">你已取消本應用權限,請手動在設置找到本應用並打開此權限</font></span>", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity2.this, "退出", Toast.LENGTH_SHORT).show();
}
}, 3000);
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
} very good!感谢楼主無私分享。
頁:
[1]