2013-03-14 51 views
0

還有一個問題。嘗試使用廣播接收器來捕捉警報(警報管理器)。Android廣播接收器給出了錯誤

使用以下代碼: 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 
+0

爲什麼你要創建一個SmsTimerService類的實例bez你在做的是正確的爲什麼 – 2013-03-14 06:03:52

回答

0

你是g設置無法實例化接收器錯誤,因爲您沒有空的構造函數,如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); 
    } 
}