[AndroidStudio] Calling Button / Permission Check & Request


1. Add user permission in manifest file
[AndroidManifest.xml]

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

2. Check if the app has permission to call. If not, request permission.

3. Set a listener on the button.

4. Create a onClick function to trigger the call.

5. Create new Intent and and start activity.

public class MainActivity extends AppCompatActivity {

    private final int MY_PERMISSIONS_CALL_PHONE=1001;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "No permission to call!", Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CALL_PHONE},
                        MY_PERMISSIONS_CALL_PHONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Button b = findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("MissingPermission")
            public void onClick(View v) {

                Context c = v.getContext();
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:01012344321"));
                c.startActivity(intent);


            }
        });
    }



}


Comments