我正在尝试使用以下方法来创建警报。它在一个简单的活动中运行良好,但现在当我尝试在我的广播接收器的onResume()函数中使用它时,它无法创建警报。
有谁知道我的代码有什么问题或有改进建议?
代码如下:
public class SmsReceiver extends BroadcastReceiver
{
private Context c;
@Override
public void onReceive(Context context, Intent intent)
{
c = context;
Bundle extras = intent.getExtras();
String body = "";
String address = "";
if ( extras != null )//if-1
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get("pdus");
for ( int i = 0; i < smsExtra.length; ++i )
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
body = sms.getMessageBody().toString();
address = sms.getOriginatingAddress();
boolean a = contactExists(context, address);
if(a == true) // if-2
{
String check = body.split("\n")[0].toLowerCase();
if(check.equals("reminder")) // if-3
{
abortBroadcast();
String[] parts = body.split("\n");
String title = parts[1];
String[] time = parts[2].split(":");
String[] date = parts[3].split("-");
String des = parts[4];
int hr = Integer.parseInt(time[0]);
int min = Integer.parseInt(time[1]);
int s = 0;
int day = Integer.parseInt(date[0]);
int mnth = Integer.parseInt(date[1]);
int year = Integer.parseInt(date[2]);
addRemInDb add = new addRemInDb();
int v = add.insert(title, hr, min, mnth, day, year, des, s);
if(v == -1)// if-4
{
Toast.makeText(context, "Title & Time Must Not Be Same",Toast.LENGTH_SHORT).show();
}
else
{
Calendar cal = Calendar.getInstance();
//Setting alarm to be triggered on specified date and time
cal.set(year, mnth, day, hr, min, s);
int requestcode= (int) cal.getTimeInMillis() * (-1);
Intent alarmIntent = new Intent(c, AlarmReceiverRem.class);
alarmIntent.putExtra("title", title);
alarmIntent.putExtra("note", des);
PendingIntent sender = PendingIntent.getService(c, requestcode, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
add.saveRequestCode(requestcode, title);
}// end of if-4
add.closeDB();
}// end of if-3
}//end of if-2
}//end of forloop
}//end of if-1
}//end of onReceive
}