Android笔记——app发送短信

  1. 添加权限
	
    
  1. 代码
    发送按钮click监听,要检查上面的两个权限(但实际上没什么用)
sendMessage1 = (Button)findViewById(R.id.sendmessage1);
        sendMessage1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1);
                } else if(ContextCompat.checkSelfPermission(MainActivity.this , Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_PHONE_STATE},2);
                }
                else {
                    sendMsg();

                }

            }
        });

发送短信的代码

 private void sendMsg() {

        String number = "18829027144";

        String content = "a";
        try{
            if (TextUtils.isEmpty(number)) {
                showToast("请输入手机号");
                return;
            }
            if (TextUtils.isEmpty(content)) {
                showToast("请输入内容");
                return;
            }
            ArrayList messages = SmsManager.getDefault().divideMessage(content);
            for (String text : messages) {
                SmsManager.getDefault().sendTextMessage(number, null, text, null, null);
            }
            showToast("Success!");
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    private void showToast(String msg){
        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
        switch(requestCode) {
            case 1:
                if(grantResults.length > 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    sendMsg();
                } else {
                    Toast.makeText(this,"您没有此权限!",Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    sendMsg();
                } else {
                    Toast.makeText(this,"您没有此权限!",Toast.LENGTH_SHORT).show();
                }
            default:
        }
    }

  1. 上述步骤完了之后,测试app还可能有无权限发送不出去的情况,这是因api23后需要动态获取权限,需要在onCreate里动态申请
		 //动态申请权限
        if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEND_SMS)!=
                PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                    Manifest.permission.SEND_SMS},1);
        }

这个代码加到onCreate里就可以了

你可能感兴趣的:(android笔记)