2012-10-03 20 views
1

我是新來的android和需要幫助,因爲問題狀態我想有一個後臺服務,偵聽傳入smses(使用廣播接收器?),然後使http請求獲取短信的身體和電話號碼一到達(上傳到網絡服務器),試圖從頭開始做,任何想法和代碼示例? :)android廣播接收器的http獲取請求

public class ReceiverContainer extends Service{ 

public SMSreceiver mSMSreceiver; 
public IntentFilter mIntentFilter; 

@Override 
public void onCreate() 
{ 
super.onCreate(); 

//SMS event receiver 
mSMSreceiver = new SMSreceiver(); 
mIntentFilter = new IntentFilter(); 
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); 
registerReceiver(mSMSreceiver, mIntentFilter); 
} 

@Override 
public void onDestroy() 
{ 
super.onDestroy(); 

// Unregister the SMS receiver 
unregisterReceiver(mSMSreceiver); 
mSMSreceiver = null; 
} 

@Override 
public IBinder onBind(Intent intent) { 
// TODO Auto-generated method stub 
return null; 
} 

public class SMSreceiver extends BroadcastReceiver 
{ 
public void Action(Context context,Intent intent) throws ClientProtocolException, URISyntaxException, IOException 
    { 
    Bundle myBundle = intent.getExtras(); 
    SmsMessage [] messages = null; 
    String strMessage = ""; 
    String msgFrom = ""; 
    String msgText = ""; 

    if (myBundle != null) 
    { 
     Object [] pdus = (Object[]) myBundle.get("pdus"); 
     messages = new SmsMessage[pdus.length]; 

     for (int i = 0; i < messages.length; i++) 
     { 
      messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
      strMessage += "SMS From: " + messages[i].getOriginatingAddress(); 
      msgFrom += messages[i].getOriginatingAddress(); 
      strMessage += " : "; 
      strMessage += messages[i].getMessageBody(); 
      msgText += messages[i].getMessageBody(); 
      strMessage += "\n"; 
     } 

     Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show(); 

     uploadMessage(context,msgFrom,msgText); 

    } 
    } 

@Override 
public void onReceive(Context context, Intent intent) 
{ 
     try { 
      Action(context,intent); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (URISyntaxException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
} 

} 

public void uploadMessage(Context context,String number,String msg) throws URISyntaxException, ClientProtocolException, IOException 
{ 

HttpResponse response = null; 
HttpClient client = new DefaultHttpClient(); 


Uri.Builder path = new Uri.Builder(); 
path.scheme("http"); 
path.authority("technonectar11.com"); 
path.path("sms"); 
path.appendQueryParameter("fromno" , number); 
path.appendQueryParameter("text" , msg); 
path.appendQueryParameter("uname" , "vijay"); 

HttpGet request = new HttpGet(path.build().toString());  
//request.setURI(new URI("http://www.technonectar11.com/sms/insertsms?fromno="+number+"&text="+msg+"&uname=vijay")); 
response = client.execute(request); 

String result = convertStreamToString(response.getEntity().getContent()); 

Toast.makeText(context, result, Toast.LENGTH_SHORT).show(); 

} 

public static String convertStreamToString(InputStream inputStream) throws IOException 
{ 
if (inputStream != null) 
{ 
    Writer writer = new StringWriter(); 

    char[] buffer = new char[1024]; 
    try 
    { 
     Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024); 
     int n; 
     while ((n = reader.read(buffer)) != -1) 
     { 
      writer.write(buffer, 0, n); 
     } 
    } 
    finally 
    { 
     inputStream.close(); 
    } 
    return writer.toString(); 
} 
else 
{ 
    return ""; 
} 

}}

這是我的全部代碼,但上載消息功能不起作用

回答

1

原來,我不允許在主線程上執行網絡操作。它給了我一個NetworkOnMainThreadException。 我必須爲這個使用IntentService/AsyncTasks/Handler。

0

這是一個WCF RESTful服務進行通信的示例代碼,客戶端代碼一定是這樣的

String uri = "http://youraddress:youport/" + serviceUri + "/" + methodName;   
HttpPost request = new HttpPost(uri); 
request.setHeader("Accept", "application/json"); 
request.setHeader("Content-type", "application/json"); 
JSONStringer requestMsg = new JSONStringer(); //you must fill data to this object 

StringEntity msg = new StringEntity(requestMsg.toString()); 
msg.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
msg.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 

request.setEntity(msg); 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(request); 

如果你使用WCF服務爲您的應用服務器,這是一個示例代碼

[ServiceContract(Namespace = "http://schema.abc.com/2012/01/MyServices")] 
public interface IMyServices{ 
    [OperationContract] 
    [WebInvoke(Method = "POST", 
       UriTemplate = "SubmitData", 
       BodyStyle = WebMessageBodyStyle.WrappedRequest, 
       ResponseFormat = WebMessageFormat.Json, 
       RequestFormat = WebMessageFormat.Json)] 
      IList<CustomeClass> SubmitData(CustomeClass message); 
} 

您必須實現自定義類,也是服務的方法體,
這是配置文件這一點,雖然你必須滿足的細節,但主要的模式是這樣的

<service name="MyServices"> 
      <endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" 
       contract="IMyServices" /> 
      </service> 

    <endpointBehaviors> 
      <behavior name="httpBehavior"> 
       <webHttp/> 
      </behavior> 
      </endpointBehaviors>