android 短信广播接收

public class SmsActivity extends AppCompatActivity {


    private Button btnSure;


    private String[] smsPermissions = {
            Manifest.permission.READ_SMS,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.SEND_SMS
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        btnSure = findViewById(R.id.btn_sure);
        registerBroadcast();

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean isHasPermission = checkPermissionAllGranted(smsPermissions);
                if (!isHasPermission){
                    ActivityCompat.requestPermissions(SmsActivity.this, smsPermissions, 200);
                }
            }
        });
    }


    private SmsReceiver smsReceiver;
    
    
    public void registerBroadcast(){
        smsReceiver = new SmsReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);
    }
    
    public void unRegisterBroadcast(){
        unregisterReceiver(smsReceiver);
    }



    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterBroadcast();
    }
}

 

public class SmsReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "我们自己的广播接收者收到信息", Toast.LENGTH_LONG).show();;
    }
    
}
    <!--  发送消息-->
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <!--  阅读消息-->
    <uses-permission android:name="android.permission.READ_SMS"/>
    <!--  写入消息-->
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <!-- 接收消息 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS" />

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页