Thứ Năm, 23 tháng 8, 2018

Android - Gửi SMS

Trong lập trình Android, bạn có thể sử dụng API SmsManager hoặc thiết bị Ứng dụng SMS tích hợp để gửi SMS. Trong hướng dẫn này, chúng tôi cho bạn thấy hai ví dụ cơ bản để gửi tin nhắn SMS -

API SmsManager

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Ứng dụng SMS tích hợp

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content"); 
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Tất nhiên, cả hai đều cần quyền SEND_SMS .

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

Ngoài phương thức trên, có vài hàm quan trọng khác có sẵn trong lớp SmsManager. Những phương pháp này được liệt kê dưới đây

Sr.No.Phương thức & Mô tả
1ArrayList <String> divideMessage (Chuỗi văn bản)

Phương thức này chia văn bản tin nhắn thành nhiều đoạn, không lớn hơn kích thước tin nhắn SMS tối đa.
2static SmsManager getDefault ()

Phương thức này được sử dụng để có được cá thể mặc định của SmsManager
3void sendDataMessage (String destinationAddress, String scAddress, short destinationPort, dữ liệu byte [], PendingIntent sentIntent, PendingIntent deliveryIntent)

Phương pháp này được sử dụng để gửi tin nhắn SMS dựa trên dữ liệu đến một cổng ứng dụng cụ thể.
4void sendMultipartTextMessage (String destinationAddress, String scAddress, ArrayList <String> các phần, ArrayList <PendingIntent> sentIntents, ArrayList <PendingIntent> deliveryIntents)

Gửi tin nhắn SMS văn bản nhiều phần.
5void sendTextMessage (String destinationAddress, String scAddress, Chuỗi văn bản, PendingIntent sentIntent, PendingIntent deliveryIntent)

Gửi tin nhắn SMS dựa trên văn bản.

Thí dụ

Ví dụ sau đây cho bạn thấy trong thực tế cách sử dụng đối tượng SmsManager để gửi một tin nhắn SMS đến số điện thoại di động nhất định.

Để thử nghiệm với ví dụ này, bạn sẽ cần thiết bị di động thực tế được trang bị hệ điều hành Android mới nhất, nếu không bạn sẽ phải đấu tranh với trình mô phỏng có thể không hoạt động.

Bậc thangSự miêu tả
1Bạn sẽ sử dụng Android Studio IDE để tạo một ứng dụng Android và đặt tên nó là hướng dẫn trong một gói com.example.tutorialspoint .
2Sửa đổi tập tin src / MainActivity.java và thêm mã cần thiết để chăm sóc gửi tin nhắn.
3Sửa đổi tệp XML bố trí res / layout / activity_main.xml thêm bất kỳ thành phần GUI nào nếu cần. Tôi đang thêm một giao diện đơn giản để có số điện thoại di động và tin nhắn văn bản được gửi đi và một nút đơn giản để gửi tin nhắn SMS.
4Không cần xác định hằng số chuỗi mặc định tại res / values ​​/ strings.xml.Android studio sẽ xử lý các hằng số mặc định.
5Sửa đổi AndroidManifest.xml như hình dưới đây
6Chạy ứng dụng để khởi chạy trình giả lập Android và xác minh kết quả của các thay đổi được thực hiện trong ứng dụng.
Sau đây là nội dung của tệp hoạt động chính đã sửa đổi src / com.example.tutorialspoint / MainActivity.java .
package com.example.tutorialspoint;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;

import android.util.Log;
import android.view.Menu;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
   private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
   Button sendBtn;
   EditText txtphoneNo;
   EditText txtMessage;
   String phoneNo;
   String message;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      sendBtn = (Button) findViewById(R.id.btnSendSMS);
      txtphoneNo = (EditText) findViewById(R.id.editText);
      txtMessage = (EditText) findViewById(R.id.editText2);

      sendBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMSMessage();
         }
      });
   }
 
   protected void sendSMSMessage() {
      phoneNo = txtphoneNo.getText().toString();
      message = txtMessage.getText().toString();
  
      if (ContextCompat.checkSelfPermission(this,
         Manifest.permission.SEND_SMS)
         != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
               Manifest.permission.SEND_SMS)) {
            } else {
               ActivityCompat.requestPermissions(this,
                  new String[]{Manifest.permission.SEND_SMS},
                  MY_PERMISSIONS_REQUEST_SEND_SMS);
            }
      }
   }
 
   @Override
   public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
      switch (requestCode) {
         case MY_PERMISSIONS_REQUEST_SEND_SMS: {
            if (grantResults.length > 0
               && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  SmsManager smsManager = SmsManager.getDefault();
                  smsManager.sendTextMessage(phoneNo, null, message, null, null);
                  Toast.makeText(getApplicationContext(), "SMS sent.", 
                     Toast.LENGTH_LONG).show();
            } else {
               Toast.makeText(getApplicationContext(), 
                  "SMS faild, please try again.", Toast.LENGTH_LONG).show();
               return;
            }
         }
      }

   }
}
Sau đây sẽ là nội dung của tệp res / layout / activity_main.xml

Ở đây abc cho biết về biểu tượng hướng dẫn
<?xml version="1.0" encoding="utf-8"?>
<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"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="MainActivity">

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Sending SMS Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Phone Number"
      android:phoneNumber="true"
      android:textColorHint="@color/abc_primary_text_material_dark"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/editText"
      android:layout_alignLeft="@+id/editText"
      android:layout_alignStart="@+id/editText"
      android:textColorHint="@color/abc_primary_text_material_dark"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton"
      android:hint="Enter SMS" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Send Sms"
      android:id="@+id/btnSendSMS"
      android:layout_below="@+id/editText2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp" />

</RelativeLayout>
Sau đây sẽ là nội dung của res / values ​​/ strings.xml để xác định hai hằng số mới
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
</resources>
Sau đây là nội dung mặc định của AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint" >
  
   <uses-permission android:name="android.permission.SEND_SMS" />
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>
Hãy thử chạy ứng dụng Android của bạn . Tôi cho rằng bạn đã kết nối thiết bị Android Mobile thực tế với máy tính của mình. Để chạy ứng dụng từ Android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ.

Trước khi bắt đầu ứng dụng của bạn, trình cài đặt Android studio sẽ hiển thị cửa sổ sau để chọn tùy chọn mà bạn muốn chạy ứng dụng Android của mình.

lập trình Android

Bây giờ bạn có thể nhập số điện thoại di động mong muốn và tin nhắn văn bản sẽ được gửi trên số đó. Cuối cùng bấm vào nút Gửi SMS để gửi tin nhắn SMS của bạn. Đảm bảo kết nối GSM / CDMA của bạn hoạt động tốt để gửi SMS của bạn tới người nhận.

Bạn có thể lấy một số tin nhắn SMS cách nhau bằng dấu phẩy và sau đó bên trong chương trình của bạn, bạn sẽ phải phân tích chúng thành một chuỗi mảng và cuối cùng bạn có thể sử dụng một vòng lặp để gửi tin nhắn đến tất cả các số đã cho. Đó là cách bạn có thể viết ứng dụng SMS của riêng mình. Phần tiếp theo sẽ hướng dẫn bạn cách sử dụng ứng dụng SMS hiện có để gửi SMS.

Sử dụng Intent tích hợp để gửi SMS

Bạn có thể sử dụng Android Intent để gửi SMS bằng cách gọi chức năng SMS tích hợp của Android. Phần sau giải thích các phần khác nhau của đối tượng Intent của chúng tôi được yêu cầu để gửi SMS.

Intent Object - Hành động gửi tin nhắn SMS

Bạn sẽ sử dụng hành động ACTION_VIEW để khởi chạy ứng dụng SMS được cài đặt trên thiết bị Android của mình. Sau đây là cú pháp đơn giản để tạo ý định với hành động ACTION_VIEW.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Mục tiêu đối tượng - Dữ liệu / Loại để gửi SMS

Để gửi một tin nhắn SMS bạn cần phải xác định smsto: như URI sử dụng phương thức setData () và kiểu dữ liệu sẽ là vnd.android-dir / mms-sms sử dụng phương thức setType () như sau:
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Thêm để gửi SMS

Android có hỗ trợ tích hợp để thêm số điện thoại và tin nhắn văn bản để gửi SMS như sau:

smsIntent.putExtra("address"  , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body"  , "Test SMS to Angilla");

Ở đây địa chỉ và sms_body là trường hợp nhạy cảm và nên được chỉ định trong ký tự nhỏ chỉ. Bạn có thể chỉ định nhiều hơn một số trong chuỗi đơn nhưng được phân tách bằng dấu chấm phẩy (;).

Thí dụ

Ví dụ sau đây cho bạn thấy cách thực tế để sử dụng đối tượng Intent để khởi chạy ứng dụng SMS để gửi SMS tới người nhận đã cho.

Để thử nghiệm với ví dụ này, bạn sẽ cần thiết bị di động thực tế được trang bị hệ điều hành Android mới nhất, nếu không bạn sẽ phải đấu tranh với trình mô phỏng có thể không hoạt động.

Bậc thangSự miêu tả
1Bạn sẽ sử dụng Android studio IDE để tạo một ứng dụng Android và đặt tên nó là tutorialspoint trong một gói com.example.tutorialspoint .
2Sửa đổi tệp src / MainActivity.java và thêm mã yêu cầu để quản lý gửi SMS.
3Sửa đổi tệp XML bố trí res / layout / activity_main.xml thêm bất kỳ thành phần GUI nào nếu cần. Tôi đang thêm một nút đơn giản để khởi chạy ứng dụng SMS Client.
4Không cần phải xác định hằng số mặc định.Android studio sẽ chăm sóc các hằng số mặc định.
5Sửa đổi AndroidManifest.xml như hình dưới đây
6Chạy ứng dụng để khởi chạy trình giả lập Android và xác minh kết quả của các thay đổi được thực hiện trong ứng dụng.
Sau đây là nội dung của tệp hoạt động chính đã sửa đổi src / com.example.tutorialspoint / MainActivity.java .
package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Button startBtn = (Button) findViewById(R.id.button);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMS();
         }
      });
   }
   
   protected void sendSMS() {
      Log.i("Send SMS", "");
      Intent smsIntent = new Intent(Intent.ACTION_VIEW);
      
      smsIntent.setData(Uri.parse("smsto:"));
      smsIntent.setType("vnd.android-dir/mms-sms");
      smsIntent.putExtra("address"  , new String ("01234"));
      smsIntent.putExtra("sms_body"  , "Test ");
      
      try {
         startActivity(smsIntent);
         finish();
         Log.i("Finished sending SMS...", "");
      } catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this, 
         "SMS faild, please try again later.", Toast.LENGTH_SHORT).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.main, menu);
      return true;
   }
}
Sau đây sẽ là nội dung của tệp res / layout / activity_main.xml

Ở đây abc cho biết về biểu tượng hướng dẫn
<?xml version="1.0" encoding="utf-8"?>
<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" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Drag and Drop Example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point "
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"
      android:textColor="#ff14be3c" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_marginTop="48dp"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Compose SMS"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="54dp"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
</RelativeLayout>
Sau đây sẽ là nội dung của res / values ​​/ strings.xml để xác định hai hằng số mới
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
</resources>
Sau đây là nội dung mặc định của AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint" >
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

Hãy thử chạy ứng dụng Android của bạn . Tôi cho rằng bạn đã kết nối thiết bị Android Mobile thực tế với máy tính của mình.

Để chạy ứng dụng từ Android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ.

Trước khi bắt đầu ứng dụng của bạn, Android studio sẽ hiển thị cửa sổ sau để chọn tùy chọn mà bạn muốn chạy ứng dụng Android của mình.
lập trình android

Chọn thiết bị di động của bạn làm tùy chọn và sau đó kiểm tra thiết bị di động của bạn sẽ hiển thị màn hình sau đây

học android
lập trình android

Bây giờ, hãy sử dụng nút Soạn SMS để khởi chạy ứng dụng SMS được tích hợp sẵn Android được hiển thị bên dưới

học android
lập trình android
Bạn có thể sửa đổi một trong các trường mặc định đã cho và cuối cùng sử dụng nút gửi SMS để gửi SMS của bạn đến người nhận đã đề cập.

Không có nhận xét nào:

Đăng nhận xét

Lập trình Android - RenderScript

Trong chương này, chúng ta sẽ tìm hiểu về Android RenderScript. Thông thường các ứng dụng trên Android được thiết kế để tiêu thụ tài nguyên ...