標籤:
小項目就要趁勝追擊,這次是實現簡訊的發送功能,東西很簡單,但那時也是值得學習的。
如下:
具體步驟:
1.首先,編寫頁面,代碼如下,沒有什麼重點。在LinearLayout布局中有個weight(權重),按比例分配大小
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context=".MainActivity" > 6 <LinearLayout 7 android:id="@+id/linear_layout" 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content"10 android:orientation="horizontal"11 android:paddingTop="5dip"12 >13 <EditText 14 android:id="@+id/edit_number"15 android:layout_width="0dip"16 android:layout_height="wrap_content"17 android:layout_weight="1"18 android:hint="@string/contact_number"19 android:inputType="phone"/>20 <Button 21 android:id="@+id/btn_send"22 android:layout_width="wrap_content"23 android:layout_height="wrap_content"24 android:text="@string/btn_send_sms"/>25 </LinearLayout>26 27 28 <EditText 29 android:id="@+id/edit_content"30 android:layout_width="match_parent"31 android:layout_height="wrap_content"32 android:lines="5"33 android:layout_below="@id/linear_layout"34 android:hint="@string/sms_content"/>35 </RelativeLayout>
2.再看看java代碼
1 public class MainActivity extends Activity implements OnClickListener{ 2 3 private EditText editContent; 4 private EditText editNumber; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main);10 editContent = (EditText) findViewById(R.id.edit_content);11 editNumber = (EditText) findViewById(R.id.edit_number);12 13 findViewById(R.id.btn_send).setOnClickListener(this);14 }15 16 @Override17 public void onClick(View view) {18 switch (view.getId()) {19 case R.id.btn_send:20 //簡訊管理器21 SmsManager manager=SmsManager.getDefault();22 String number=editNumber.getText().toString();23 String content=editContent.getText().toString();24 25 manager.sendTextMessage(number, null, content, null, null);26 break;27 28 default:29 break;30 }31 }32 }
簡訊這邊沒有像撥號器那樣調用系統內建的,直接調用SmsManager簡訊管理器來傳送簡訊,其中sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)方法的四個參數,第一個參數是一個字串類型,直接翻譯就是目標地址,其實就是收信人的手機號碼,第二個參數也是一個字串類型,是簡訊服務中心,一般為null,就是用當前預設的簡訊服務中心(沒去瞭解)。第三個參數也是簡訊的內容了,第四個參數是一個PendingIntent,當訊息發出時,成功或者失敗的資訊報告通過PendingIntent來廣播,暫時就為null。第四個參數也是個PendingIntent,當訊息發送到收件者時,該PendingIntent會被廣播,暫時也為null。
3.最後就是給應用傳送簡訊的許可權,在資訊清單檔中添加如下代碼
<uses-permission android:name="android.permission.SEND_SMS"/>
完了,可以試試看,無論在真機還是模擬器上,代碼不複雜,這也是學到點東西的,功能還可以更好的完善,那是以後學習中在添加了。
也請大家多多指教!!!!
Android初學項目——簡訊發送器