还有另外一个问题。尝试使用广播接收器来捕捉警报(警报管理器)。
使用以下代码: 包com.suncco.shangxinbao.service;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.suncco.shangxinbao.model.ScheduledSms;
public class SmsTimerService extends BroadcastReceiver {
public SmsTimerService(Context context, int timeoutInSeconds,
ScheduledSms sms) {
Intent myIntent = new Intent(context, SmsTimerService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
sms.getRequestCodeForListener(), myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5); // should be timeoutInSeconds instead of 5
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.w("Karl", "yay");
}
在清单中我把它作为接收者:
<receiver
android:name="com.suncco.shangxinbao.service.SmsTimerService"
android:process=":remote" />
我像这样制作了一个SmsTimerService的对象:
SmsTimerService smsTimerService = new SmsTimerService(this,5,sms);
这是众所周知的错误......
java.lang.RuntimeException: Unable to instantiate receiver
com.suncco.shangxinbao.service.SmsTimerService: java.lang.InstantiationException:
com.suncco.shangxinbao.service.SmsTimerService
答案 0 :(得分:0)
您无法实例化接收器错误,因为您没有空构造函数,例如 SmsTimerService()。关键是你需要一个空的构造函数来接收意图时创建这个接收器。 如果你没有实现任何构造函数,那就没关系。但是,如果使用参数实现构造函数,则还需要实现空的构造函数!
所以你可以做这样的事情。请注意,在创建意图时,我没有研究你真正想做的事情。
public class SmsTimerService extends BroadcastReceiver {
private void doAction(Context context, int timeoutInSeconds, ScheduledSms sms) {
Intent myIntent = new Intent(context, SmsTimerService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
sms.getRequestCodeForListener(), myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5); // should be timeoutInSeconds instead of
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
// you get to replace sms with something!
doAction(context, 5, sms); // original u do - > new SmsTimerService(this,5,sms);
}
}