0

还有一个问题。试图使用广播接收器来触发警报(警报管理器)。

使用如下代码:package 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
4

1 回答 1

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);
    }
}
于 2013-03-14T06:25:34.780 回答