Я работаю над приложением для Android, которое должно прослушивать как входящие, так и исходящие SMS-сообщения, форматировать их в JSON и отправлять на мой локальный сервер Flask. Я следовал различным руководствам и руководствам и считаю, что мой код правильный, но столкнулся с неприятной проблемой: я получаю только входящие SMS-сообщения, а не исходящие.
Вот краткое изложение того, что я сделал:
Разрешения: у меня есть разрешения RECEIVE_SMS, READ_SMS, SEND_SMS, INTERNET и FOREGROUND_SERVICE, объявленные в моем AndroidManifest.xml.
Foreground Служба: моя служба SmsListenerService работает как служба переднего плана с постоянным уведомлением.
BroadcastReceiver: у меня есть BroadcastReceiver внутри моей службы, который прослушивает действия Telephony.Sms.Intents.SMS_RECEIVED_ACTION и «android.provider.Telephony.SMS_SENT». .
Создание и отправка JSON: код для создания объекта JSON и отправки его на сервер, похоже, работает нормально для входящих SMS, но не срабатывает для исходящих.
Тестирование: я тестирую на физическом устройстве и пытались отправить SMS на несколько номеров.
Фрагмент кода (SmsListenerService):
package de.dlyt.yanndroid.notifer.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import de.dlyt.yanndroid.notifer.MainActivity;
import de.dlyt.yanndroid.notifer.R;
public class SmsListenerService extends Service {
private static final String TAG = "SmsListenerService";
private static final String CHANNEL_ID = "sms_listener_channel";
private static final int NOTIFICATION_ID = 1;
private BroadcastReceiver smsReceiver = new SMSReceiver();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("SMS Listener")
.setContentText("Listening for SMS...")
// .setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build();
startForeground(NOTIFICATION_ID, notification);
return START_STICKY;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "SMS Listener Channel";
String description = "Channel for SMS Listener notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "SMS Service created");
IntentFilter filter = new IntentFilter();
filter.addAction(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
filter.addAction("android.provider.Telephony.SMS_SENT");
registerReceiver(smsReceiver, filter, Context.RECEIVER_EXPORTED);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
public static class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
String messageBody = smsMessages[0].getMessageBody();
Log.d("Andrew","Hello");
Log.d("Andrew",messageBody);
// if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action) ||
// "android.provider.Telephony.SMS_SENT".equals(action)) {
if (true){
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String address = smsMessage.getOriginatingAddress();
String body = smsMessage.getMessageBody();
long timestamp = smsMessage.getTimestampMillis();
JSONObject jsonSms = new JSONObject();
String deviceName = Build.MODEL;
try {
jsonSms.put("deviceName", deviceName != null ? deviceName : "Unknown Device");
jsonSms.put("appName", Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action) ? "incoming" : "outgoing");
jsonSms.put("packageName", Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action) ? "incoming" : "outgoing");
jsonSms.put("id",0);
jsonSms.put("time", timestamp);
jsonSms.put("isOngoing",false);
jsonSms.put("Notification Extra","");
jsonSms.put("title", address);
jsonSms.put("text", body); // Added "body" as the key
jsonSms.put("subText", "");
jsonSms.put("titleBig", "");
jsonSms.put("bigText", "");
jsonSms.put("progressIndeterminate", 0);
jsonSms.put("progressMax",0);
jsonSms.put("progress",0);
jsonSms.put("interruptionFilter",0);
// Send the JSON object to your server
sendToServer(jsonSms.toString(), context);
} catch (JSONException e) {
Log.e(TAG, "Error creating JSON object", e);
}
}
}
}
private static void sendToServer(String jsonData, Context context) {
String serverUrl = "http://**.***.**.***:8000"; // Your server URL
new Thread(() -> {
HttpURLConnection conn = null;
try {
URL url = new URL(serverUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d(TAG, "SMS data sent successfully.");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
Log.d(TAG, "Server response: " + response.toString());
} else {
Log.e(TAG, "Error sending SMS data. Response Code: " + responseCode);
}
} catch (IOException e) {
Log.e(TAG, "IOException while sending SMS data:", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}).start();
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... text-messa
Android: моя функция onReceive получает только входящие, а не исходящие текстовые сообщения ⇐ Android
Форум для тех, кто программирует под Android
1720142006
Anonymous
Я работаю над приложением для Android, которое должно прослушивать как входящие, так и исходящие SMS-сообщения, форматировать их в JSON и отправлять на мой локальный сервер Flask. Я следовал различным руководствам и руководствам и считаю, что мой код правильный, но столкнулся с неприятной проблемой: я получаю только входящие SMS-сообщения, а не исходящие.
Вот краткое изложение того, что я сделал:
Разрешения: у меня есть разрешения RECEIVE_SMS, READ_SMS, SEND_SMS, INTERNET и FOREGROUND_SERVICE, объявленные в моем AndroidManifest.xml.
Foreground Служба: моя служба SmsListenerService работает как служба переднего плана с постоянным уведомлением.
BroadcastReceiver: у меня есть BroadcastReceiver внутри моей службы, который прослушивает действия Telephony.Sms.Intents.SMS_RECEIVED_ACTION и «android.provider.Telephony.SMS_SENT». .
Создание и отправка JSON: код для создания объекта JSON и отправки его на сервер, похоже, работает нормально для входящих SMS, но не срабатывает для исходящих.
Тестирование: я тестирую на физическом устройстве и пытались отправить SMS на несколько номеров.
Фрагмент кода (SmsListenerService):
package de.dlyt.yanndroid.notifer.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import de.dlyt.yanndroid.notifer.MainActivity;
import de.dlyt.yanndroid.notifer.R;
public class SmsListenerService extends Service {
private static final String TAG = "SmsListenerService";
private static final String CHANNEL_ID = "sms_listener_channel";
private static final int NOTIFICATION_ID = 1;
private BroadcastReceiver smsReceiver = new SMSReceiver();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("SMS Listener")
.setContentText("Listening for SMS...")
// .setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build();
startForeground(NOTIFICATION_ID, notification);
return START_STICKY;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "SMS Listener Channel";
String description = "Channel for SMS Listener notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "SMS Service created");
IntentFilter filter = new IntentFilter();
filter.addAction(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
filter.addAction("android.provider.Telephony.SMS_SENT");
registerReceiver(smsReceiver, filter, Context.RECEIVER_EXPORTED);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
public static class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
String messageBody = smsMessages[0].getMessageBody();
Log.d("Andrew","Hello");
Log.d("Andrew",messageBody);
// if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action) ||
// "android.provider.Telephony.SMS_SENT".equals(action)) {
if (true){
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String address = smsMessage.getOriginatingAddress();
String body = smsMessage.getMessageBody();
long timestamp = smsMessage.getTimestampMillis();
JSONObject jsonSms = new JSONObject();
String deviceName = Build.MODEL;
try {
jsonSms.put("deviceName", deviceName != null ? deviceName : "Unknown Device");
jsonSms.put("appName", Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action) ? "incoming" : "outgoing");
jsonSms.put("packageName", Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action) ? "incoming" : "outgoing");
jsonSms.put("id",0);
jsonSms.put("time", timestamp);
jsonSms.put("isOngoing",false);
jsonSms.put("Notification Extra","");
jsonSms.put("title", address);
jsonSms.put("text", body); // Added "body" as the key
jsonSms.put("subText", "");
jsonSms.put("titleBig", "");
jsonSms.put("bigText", "");
jsonSms.put("progressIndeterminate", 0);
jsonSms.put("progressMax",0);
jsonSms.put("progress",0);
jsonSms.put("interruptionFilter",0);
// Send the JSON object to your server
sendToServer(jsonSms.toString(), context);
} catch (JSONException e) {
Log.e(TAG, "Error creating JSON object", e);
}
}
}
}
private static void sendToServer(String jsonData, Context context) {
String serverUrl = "http://**.***.**.***:8000"; // Your server URL
new Thread(() -> {
HttpURLConnection conn = null;
try {
URL url = new URL(serverUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d(TAG, "SMS data sent successfully.");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
Log.d(TAG, "Server response: " + response.toString());
} else {
Log.e(TAG, "Error sending SMS data. Response Code: " + responseCode);
}
} catch (IOException e) {
Log.e(TAG, "IOException while sending SMS data:", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}).start();
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78709341/android-my-onreceive-function-only-getting-incoming-and-not-outgoing-text-messa[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия