2015-09-26 68 views
-1

我需要開發一個應用程序,該應用程序在用戶設備到達時立即讀取用戶SMS消息,然後以JSON數據的形式提取併發送到Web服務器。 我是新來的android開發。 我們將跟蹤的消息將來自+252898,除了一些額外的信息外,這些消息在內容中很常見,所以我們需要的是使用JSON數據將附加內容發送到我們的Web應用程序。 樣本消息來自+252898。Android如何開發短信應用程序,它將接收用戶消息並以JSON格式發送

enter image description here

回答

3

有涉及2個組件,收到短信時的邏輯和分析數據,並把數據發送到你的Web應用程序的邏輯。

爲了在收到短信時獲得工作的「掛鉤」,您需要使用SMS_RECEIVED意圖構建廣播接收器。

在您的應用程序,創建一個新的BroadcastReceiver叫MySMSReceiver和接收器添加到清單:

<receiver android:name=".MySMSReceiver"> 
    <intent-filter> 
     <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter> 
</receiver> 

此外,添加的權限清單,以便能夠接收和閱讀短信:

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

現在這裏是部分代碼,你將有接收器:

public class MySMSReceiver extends BroadcastReceiver { 

    public void onReceive(Context context, Intent intent) { 

    } 
} 

現在,當您在手機上收到短信時,您的廣播接收機將運行其onReceive方法,因爲您的意圖過濾器明確指定了SMS_RECIVED意圖。

使用SMS_RECEIVED意圖(在onReceive方法中接收到的參數),您可以讀取的意圖內會有幾個附加項。內的onReceive,您可以添加類似的邏輯以下內容:

Bundle bundle = intent.getExtras(); 
if (bundle != null) {  
    Object[] pdus = (Object[]) bundle.get("pdus"); 
    for (int i = 0; i < pdus.length; i++) { 
     SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]); 
     String senderNumber = message.getDisplayOriginatingAddress(); 
     String messageContent = message.getDisplayMessageBody(); 
    } 
} 

如上,你便要確保該消息是通過檢查senderNumber或在messageContent您感興趣的。許多應用程序嘗試使用正則表達式模式匹配來確保當前收到的消息符合應用程序的興趣。

現在您需要構建您的JSON對象並將其發佈到您的服務器。

導入幾個班,以您的接收器,並創建一個郵政法後的邏輯來構造一個JSON對象發送到你的Web應用程序:現在

import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONObject; 

public void Post(string number, string message){ 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost("your web api url here"); 
      JSONObject jsonObject = new JSONObject(); 
      jsonObject.accumulate("number", number); 
      jsonObject.accumulate("message", message); 
      StringEntity se = new StringEntity(jsonObject.ToString()); 
      httpPost.setEntity(se); 
      httpPost.setHeader("Accept", "application/json"); 
      httpPost.setHeader("Content-type", "application/json"); 
      httpclient.execute(httpPost); 

     } catch (Exception e) { 
     } 
    } 

當然,如果你想讀的響應POST,您可以閱讀httpclient.execute(httpPost)的返回值。

現在邏輯完成了,你只需要把這些部分放在一起就可以滿足你的需要。

相關問題