自动回复接收到的广播消息。

huangapple go评论87阅读模式
英文:

Automatically reply to Message recieved by Broadcastreciever

问题

以下是翻译好的部分:

public class MyReceiver extends BroadcastReceiver {
    public static String textSmsbody = "";
    private static final String TAG = MyReceiver.class.getSimpleName();
    public static final String pdu_type = "pdus";

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) {
        // 获取短信消息。
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs;
        String strMessage = "";
        String format = bundle.getString("format");
        // 检索接收到的短信消息。
        Object[] pdus = (Object[]) bundle.get(pdu_type);
        if (pdus != null) {
            // 检查Android版本。
            boolean isVersionM = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
            // 填充msgs数组。
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                // 检查Android版本并使用适当的createFromPdu。
                if (isVersionM) {
                    // 如果是Android版本M或更新版本:
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    // 如果是Android版本L或更早版本:
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }
                // 构建要显示的消息。
                String a = msgs[i].getMessageBody();
                textSmsbody = msgs[i].getMessageBody();
                if (a.contains("?")) {
                    strMessage = msgs[i].getOriginatingAddress();
                } else {
                    strMessage = a;
                }
                // 记录和显示短信消息。
                Log.d(TAG, "onReceive: " + strMessage);
                Toast.makeText(context, strMessage, Toast.LENGTH_LONG).show();
            }
        }
    }
}
public void smsSendMessage(View view) {
    databaseSearch();
    String destinationAddress = "2020";
    String smsMessage = sendingText;
    String scAddress = null;
    PendingIntent sentIntent = null, deliveryIntent = null;
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(
            destinationAddress, scAddress, smsMessage,
            sentIntent, deliveryIntent);
}

请注意,这是您提供的代码的翻译部分。如果您需要更多帮助或其他部分的翻译,请随时告诉我。

英文:

Good day everyone.

I would like to make an application which replies to received SMS automatically.
For example.

Jon Doe sends me - "Hi", Application gets the message body, checks it with my database where I have a potential response:

ID | Text | Potential Answer
01 | Hi | Hello how are you?

and Application sends the Potential response.

So far what I have achieved -
App receives the Message, checks it with the database ( using Like '%') and gets the correct "Potential Answer" Column and passes it as message text body, but to send it I am using a button.

My Reciever is a sperate file class

public class MyReceiver extends BroadcastReceiver {
public static String textSmsbody=&quot;&quot;;
private static final String TAG=MyReceiver.class.getSimpleName();
public static final String pdu_type=&quot;pdus&quot;;
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onReceive(Context context, Intent intent) {
// Get the SMS message.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
String strMessage = &quot;&quot;;
String format = bundle.getString(&quot;format&quot;);
// Retrieve the SMS message received.
Object[] pdus = (Object[]) bundle.get(pdu_type);
if (pdus != null) {
// Check the Android version.
boolean isVersionM =
(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M);
// Fill the msgs array.
msgs = new SmsMessage[pdus.length];
for (int i = 0; i &lt; msgs.length; i++) {
// Check Android version and use appropriate createFromPdu.
if (isVersionM) {
// If Android version M or newer:
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
} else {
// If Android version L or older:
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
// Build the message to show.
String a=msgs[i].getMessageBody();
textSmsbody=msgs[i].getMessageBody();
if (a.contains(&quot;?&quot;)) {
strMessage=msgs[i].getOriginatingAddress();
// strMessage += &quot; :&quot; + msgs[i].getMessageBody() + &quot;\n&quot;;
}
else {
strMessage=a;
//  strMessage += &quot;SMS from&quot; + msgs[i].getOriginatingAddress();
// strMessage += &quot;ELSE:&quot; + msgs[i].getMessageBody() + &quot;\n&quot;;
}
// Log and display the SMS message.
Log.d(TAG, &quot;onReceive: &quot; + strMessage);
Toast.makeText(context, strMessage, Toast.LENGTH_LONG).show();
}
}
}
}

Sending method is in my MainActivity.

public  void smsSendMessage(View view) {
databaseSearch();
// Set the destination phone number to the string in editText.
String destinationAddress = &quot;2020&quot;;
// Find the sms_message view.
// Get the text of the SMS message.
String smsMessage = sendingText;
// Set the service center address if needed, otherwise null.
String scAddress = null;
// Set pending intents to broadcast
// when message sent and when delivered, or set to null.
PendingIntent sentIntent = null, deliveryIntent = null;
// Use SmsManager.
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage
(destinationAddress, scAddress, smsMessage,
sentIntent, deliveryIntent);
}

In layout I have a button which calls smsSendMessage () ;

My question is how I can make it automatically without button.

When the phone receives a message, the app shall check it with the database and send it by itself.

Please tell me if you need to see my Manifest file, or databasehelper.

答案1

得分: 1

**在您的情况下使用 JobService 应该是一个合适的选项**

*创建一个类似这样的 JobService 类*

```java
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ExampleJobService extends JobService {
    
    @Override
    public boolean onStartJob(JobParameters params) {
        // 发送一条消息
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }
}

同时在您的清单文件中进行声明:

<service
    android:name=".ExampleJobService"
    android:permission="android.permission.BIND_JOB_SERVICE" />

现在在您的 Receiver 中,您可以这样启动它:

ComponentName componentName = new ComponentName(context, ExampleJobService.class);

PersistableBundle bundle = new PersistableBundle();
bundle.putLong("lat", lat);
bundle.putLong("lon", lon);

JobInfo jobInfo = new JobInfo.Builder(0, componentName)
        .setExtras(bundle)
        .build();

更多关于 JobServices 的详细信息请参阅:https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html


<details>
<summary>英文:</summary>
**Using JobService should be a suitable option in your case.**
*Create a JobService class like that*
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ExampleJobService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
//send a message
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
Also Declare In your Manifest
&lt;service
android:name=&quot;.ExampleJobService&quot;
android:permission=&quot;android.permission.BIND_JOB_SERVICE&quot; /&gt;
Now in your Receiver, you can start it like that
ComponentName componentName = new ComponentName(context, ExampleJobService.class);
PersistableBundle bundle = new PersistableBundle();
bundle.putLong(&quot;lat&quot;, lat);
bundle.putLong(&quot;lon&quot;, lon);
JobInfo jobInfo = new JobInfo.Builder(0, componentName)
.setExtras(bundle)
.build();
For more details about JobServices https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html
</details>

huangapple
  • 本文由 发表于 2020年4月6日 18:27:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/61057698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定