2014-01-25 2 views
0

im пытается написать приложение для Android, которое второе отправляет sms на мой телефон, оно загружает его или отправляет на мой сервер в Интернете, я пишу новый номер sms и часть тела, но теперь я не знаю, должен ли он писать senderNum и Message в файл и загружать его или его можно отправить прямо на мой интернет-сервер, любую идею? PLZ скажите мне с кодом samle. спасибо ..Отправить мои входящие SMS-сообщения на мой сервер (загрузить или ..)

public class IncomingSms extends BroadcastReceiver { 

    // Get the object of SmsManager 
    final SmsManager sms = SmsManager.getDefault(); 
    private void sendSMS(String phoneNumber, String message) 
    { 
     SmsManager sms = SmsManager.getDefault(); 
     sms.sendTextMessage(phoneNumber, null, message, null, null); 
    } 

    public void onReceive(Context context, Intent intent) { 
     // Retrieves a map of extended data from the intent. 
     final Bundle bundle = intent.getExtras(); 

     try { 
      if (bundle != null) { 
       final Object[] pdusObj = (Object[]) bundle.get("pdus"); 

       for (int i = 0; i < pdusObj.length; i++) { 
        SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); 
        String phoneNumber = currentMessage.getDisplayOriginatingAddress(); 

        String senderNum = phoneNumber; 
        String message = currentMessage.getDisplayMessageBody(); 
        String sindrome = senderNum + message; 

        Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message); 
        sendSMS("15555215554", sindrome); 
       } // end for loop 
      } // bundle is null 

     } catch (Exception e) { 
      Log.e("SmsReceiver", "Exception smsReceiver" +e); 
     } 
    } 

    private byte[] getBytes() { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    private OutputStream openFileOutput(String string, int modePrivate) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
} 
+0

Напишите простой веб-сервисный сервис с требуемыми параметрами и разверните его на своем сервере. Возьмите URL-адрес и удалите его со своего мобильного телефона, и на сервере напишите свою логику, чтобы сохранить его. – pyus13

ответ

0

Это идея, вы можете использовать MySQL DB и файл PHP.

Файл PHP будет заботиться о сохранить смс в БД, и это может быть что-то вроде

<?php 
// You should consider the idea to put everything in POST request and add "key" values to avoid someone to 
// send to your server 1000 sms from the web with just a page reload 

$from = $_GET['from']; 
$body = $_GET['body']; 

if (!is_numeric($from)) 
{ 
    // Invalid input 
    // Do nothing 
    exit(); 
} 

// connect to the MYSQL server 
$mysqli = new MySQLi(...); 

/* 
* DB: 
* PHONE NUMBER | BODY 
* X   | X 
* 
* You can anyway add more info like sending time etc. 
*/ 

// run the query insert 
if ($stmt = $mysqli->prepare("INSERT INTO sms (number, body) VALUES (?, ?)")) 
{ 
    $stmt->bind_param("is", $from, $body); 
    $stmt->execute(); 
    $stmt->close(); 
} 
// now you have in your database the sms 

// close mysqli connection 
$mysqli->close(); 


?> 

Затем вы можете использовать AsyncTask или обработчика для выполнения запроса из приложения Android.

Хорошо, возможно, я пропустил что-то вроде близкого ресурса .. но все должно быть в порядке.

// As number i think SenderNumber is the number of who send the SMS 
// message is here the message is saved 
Handler handler = new Handler(); 
handler.post(new Runnable() { 
    @Override 
    public void run() { 
     // OK 
     // Here you have senderNum and message 

     HttpClient httpClient = new DefaultHttpClient(); 
     // Since it's a GET reuqest you can pass params directly 
     // but as i said, a POST could be more better 
     HttpGet httpGet = new HttpGet("YOUR_URL_HERE?number=" + number + "&body=" + message); 
     String responseBody; 
     HttpResponse response; 

     try 
     { 
      // We run the request 
      response = httpClient.execute(httpGet); 

      // now i need to know if everything is ok 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 

      // OK! 
      if (statusCode == 200) 
      { 
       responseBody = EntityUtils.toString(response.getEntity()); 
       // Now in responseBody you have the response of the request 
       // If you don't need it, remove it 
      } 

     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
}); 

Это должно помочь вам понять, как вы можете сделать код.

+0

спасибо за вашу идею, ее отличная .. я бы действительно оценил, если бы вы могли сказать больше о стороне android, переменные числа и тела - senderNum и сообщение в моем коде, как я могу отправить его на сервер ??! – user2971833

+0

О да, подождите немного. –

+0

Я отредактировал ответ, это вам поможет? (извините за покой, я был занят .. но код тоже должен быть в порядке.) –

Смежные вопросы