android-emulator how - Android App to call a number on button click




code dial (7)

I want to call a number given in a textbox but I'm getting the error:

The application 'xyz'(process com.android) has stopped unexpectedly

The following is my code. Where is it going wrong?

EditText txtPhn;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button callButton = (Button)findViewById(R.id.btnCall);
    txtPhn = (EditText)findViewById(R.id.txtPhnNumber);
    callButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            try {
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:"+txtPhn.getText().toString()));
                    startActivity(callIntent);
                } catch (ActivityNotFoundException activityException) {
                    Log.e("Calling a Phone Number", "Call failed", activityException);
                }
        }
    });
}

EDITED LogCat

03-09 11:23:25.874: ERROR/AndroidRuntime(370): FATAL EXCEPTION: main
03-09 11:23:25.874: ERROR/AndroidRuntime(370): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx-xxx-xxxx flg=0x10000000 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{40738d70 370:org.krish.android/10034} (pid=370, uid=10034) requires android.permission.CALL_PHONE
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.os.Parcel.readException(Parcel.java:1322)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.os.Parcel.readException(Parcel.java:1276)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1351)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1374)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.app.Activity.startActivityForResult(Activity.java:2827)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.app.Activity.startActivity(Activity.java:2933)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at org.krish.android.caller$1.onClick(caller.java:29)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.view.View.performClick(View.java:2485)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.view.View$PerformClick.run(View.java:9080)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.os.Handler.handleCallback(Handler.java:587)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.os.Looper.loop(Looper.java:123)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at java.lang.reflect.Method.invokeNative(Native Method)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at    java.lang.reflect.Method.invoke(Method.java:507)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-09 11:23:25.874: ERROR/AndroidRuntime(370):     at dalvik.system.NativeStart.main(Native Method)`enter code here`

Answers

You might want to try the following approach:

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+txtPhn.getText().toString()));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(callIntent);

I.e. adding the callIntent.setFlags(...) function call.


Make sure you have added the <uses-permission ... /> tag at a correct level in the AndroidManifest.xml file (outside the <application ... /> tag but within the <manifest ... /> tag):

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dbm.pkg"
    android:versionCode="1"
    android:versionName="1.0">

    <!-- NOTE! Your uses-permission must be outside the "application" tag
               but within the "manifest" tag. -->

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

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name">

        <!-- Insert your other stuff here -->

    </application>

    <uses-sdk android:minSdkVersion="9" />
</manifest> 

Try adding trim():

callIntent.setData(Uri.parse("tel:"+txtPhn.getText().toString().trim()));

There are two intents to call/start calling: ACTION_CALL and ACTION_DIAL.

ACTION_DIAL will only open the dialer with the number filled in, but allows the user to actually call or reject the call. ACTION_CALL will immediately call the number and requires an extra permission.

So make sure you have the permission

uses-permission android:name="android.permission.CALL_PHONE"

in your AndroidManifest.xml


You probably need to test it on a real device. I faced the same problem and it worked on the real device. Calling and GPS both sometimes dont work as expected in AVD.


API 24

Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:+94720999666"));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    startActivity(intent);

and also add

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

My final working JAVA and PHP code to upload a file from the Android's SD card to my own Web Server.

The Java/Android Code:

private void doFileUpload() {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";
    String urlString = "http://mywebsite.com/directory/upload.php";

    try {

        //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {

            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // close streams
        Log.e("Debug", "File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();

    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }

    //------------------ read the SERVER RESPONSE
    try {

        inStream = new DataInputStream(conn.getInputStream());
        String str;

        while ((str = inStream.readLine()) != null) {

            Log.e("Debug", "Server Response " + str);

        }

        inStream.close();

    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
}

The associated PHP code to go on your server (upload.php):

<?php
// Where the file is going to be placed 
$target_path = "uploads/";

/* Add the original filename to our target path.  
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
    chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;
}
?>

Things to note.
1) I had "mypic.png" within the root directory of the SD card. As in, if you looked at the Android device through Mass Storage USB view you would put the file in the first directory you come across.

2) USB MASS STORAGE MUST BE TURNED OFF ON THE PHONE! Or just completely unplug it from the computer you are writing the code on to assure this is the case.

3) I had to create an "uploads" folder in the same directory as my php file.

4) You obviously must change the web address I have written as http://mywebsite.com/directory/upload.php to be your own website.





android android-emulator