android development basics tutorial call and text

  • 2020-05-09 19:13:44
  • OfStack

Call and text demo
 
public class MainActivity extends Activity { 
EditText mPhoneNum,mMessage; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
mPhoneNum=(EditText) findViewById(R.id.editText1); 
mMessage=(EditText) findViewById(R.id.editText2); 
} 
public void onClick(View v) { 
int id = v.getId(); 
String phoneNo = mPhoneNum.getText().toString(); 
// call  
if(id == R.id.button1){ 
Intent i = new Intent(); 
// Set action name  
i.setAction("android.intent.action.CALL"); 
// Set intent data  
i.setData(Uri.parse("tel:" + phoneNo)); 
// Start activities  
startActivity(i); 
} 
// texting  
else if(id == R.id.button2){ 
String smsContent = mMessage.getText().toString(); 
// Get the default SMS manager  
SmsManager sm = SmsManager.getDefault(); 
sm.sendTextMessage(phoneNo, null, smsContent, null, null); 
// Prompt user information , Interim notice  
Toast toast = Toast.makeText(MainActivity.this, " Send complete ", Toast.LENGTH_LONG); 
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 50, 100); 
toast.show(); 
} 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
getMenuInflater().inflate(R.menu.activity_main, menu); 
return true; 
} 
} 

Layout code:
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity" > 
<Button 
android:id="@+id/button1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_alignParentTop="true" 
android:onClick="onClick" 
android:text=" Make a phone call " /> 
<Button 
android:id="@+id/button2" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentTop="true" 
android:layout_toRightOf="@+id/button1" 
android:onClick="onClick" 
android:text=" texting " /> 
<EditText 
android:id="@+id/editText1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_below="@+id/button1" 
android:ems="10" 
android:hint=" Please enter the telephone number " 
android:inputType="number" > 
<requestFocus /> 
</EditText> 
<EditText 
android:id="@+id/editText2" 
android:layout_width="wrap_content" 
android:layout_height="100dip" 
android:layout_alignParentLeft="true" 
android:layout_below="@+id/editText1" 
android:hint=" Please enter the text message " 
android:ems="10" /> 
</RelativeLayout> 

Related articles: