Trying to send SMS to telegram group whenever we receive new SMS. I tried to run below code but when new SMS arrives, there is no activity.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String TELEGRAM_BOT_TOKEN = "1234:ABC";
private static final String TELEGRAM_CHAT_ID = "-5678";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String messageBody = smsMessage.getMessageBody();
sendToTelegram(messageBody);
}
}
}
}
};
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, filter);
}
private void sendToTelegram(String message) {
new Thread(() -> {
try {
URL url = new URL("https://api.telegram.org/bot" + TELEGRAM_BOT_TOKEN + "/sendMessage");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("chat_id", TELEGRAM_CHAT_ID);
jsonParam.put("text", message);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(jsonParam.toString());
wr.flush();
int responseCode = urlConnection.getResponseCode();
Log.d("TelegramResponse", "Response Code: " + responseCode);
urlConnection.disconnect();
} catch (Exception e) {
Log.e("TelegramError", "Error sending message to Telegram: " + e.getMessage());
}
}).start();
}
}
I sent a test message to the number where the app is installed but when new SMS arrives, there is no activity. Not sending anything in telegram and o Log detected in logcat