当我的手机重新启动时,我尝试发送短信。我的代码正在进行活动,我可以在活动中获取发送报告。但是我在Broadcastreceiver中放了相同的代码,它无法正常工作。
try
{
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context arg0, Intent arg1)
{
int resultCode = getResultCode();
switch (resultCode)
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(), "Generic failure",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(), "No service",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(), "Null PDU",Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(getBaseContext(), "Radio off",Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendTextMessage(address, null,"Send sms", sentPI, null);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage()+"!\n"+"Failed to send SMS", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
如何在broadcastreceiver或服务中使用此代码?。
答案 0 :(得分:0)
您无法在BroadcastReceiver
中注册BroadcastReceiver
,因为BroadcastReceiver
的有效期不长(仅限于onReceive()
的通话时间。所以您需要的是什么要做的是从Service
开始BroadcastReceiver
并让它发送短信。您所拥有的代码应该来自Service
。
答案 1 :(得分:0)
不要使用 SmsManager.RESULT_ERROR_GENERIC_FAILURE:,因为它已弃用,而是使用android.telephony.SmsManager Docs
重启后,请致电广播接收器:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, YourService.class);
context.startService(service);
}
}
您的服务:
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.Toast;
public class YourService extends Service {
@Override
public void onCreate() {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
//
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number to send , null, text, null, null);
}
@Override
public boolean onUnbind(Intent intent) {
}
}
确保您在清单文件中添加所需的权限,接收方和服务