我想在没有用户干预的情况下发送短信,所以我创建了一个BroadcastReceiver
来解决这个问题。这BroadcastReceiver
将在启动时收到"BOOT_COMPLETED"
通知。在该OnReceive
功能中,我们可以发送短信(开机 5 分钟后)。我试过这个逻辑,但它不起作用。
我从这个网站上的其他帖子了解到,在 Android 3.1+ 之后,我们无法使用这种逻辑来满足这个要求。但是我在 Android 2.3 上尝试了这个逻辑,它似乎也不起作用。
请向我建议如何在 Android 2.3 和 Android 4.0+ 版本上解决此问题。我不想为此要求创建任何 UI。
我正在尝试遵循一段代码。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.telephony.SmsManager;
import android.util.Log;
class MyCountDownTimer extends CountDownTimer {
private int no_of_attempts;
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
no_of_attempts = 0;
}
@Override
public void onFinish() {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+9198104084753", null, "Test Message ", null, null);
} catch (Exception e) {
Log.d("BGSMS","SMS Sending failed..Try to resend SMS");
no_of_attempts++;
if (no_of_attempts <= 3)
{
long startTime = 5 * 1000;
long interval = 1 * 1000;
CountDownTimer countDownTimer;
countDownTimer = new MyCountDownTimer(startTime, interval);
countDownTimer.start();
}
}
}
@Override
public void onTick(long millisUntilFinished) {
}
}
public class SalestrackerReceiver extends BroadcastReceiver {
private CountDownTimer countDownTimer;
private final long startTime = 5 * 1000;
private final long interval = 1 * 1000;
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Anshul","Anshul Broadcast receiver received");
countDownTimer = new MyCountDownTimer(startTime, interval);
countDownTimer.start();
}
}
Manifest File :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sales_tracker"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="SalestrackerReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>