2017-07-18 80 views
0

使用以下代碼,AlarmReceiver.onReceive()在應用程序被手動終止後(以模擬操作系統在奇思妙想中終止應用程序)時不會被調用。AlarmReceiver沒有喚醒應用程序

我該怎麼做才能在操作系統殺死它之後AlarmReceiver仍能正常工作?

清單:

<receiver 
     android:name="abc.def.AlarmReceiver" 
     android:enabled="true" 
     android:exported="false" 
     /> 

AlarmReceiver:

public class AlarmReceiver extends BroadcastReceiver { 
    public void setupAlarm(Context context, int intervalMS) { 
     this.interval = interval; 

     Calendar updateTime = Calendar.getInstance(); 

     updateTime.add(Calendar.SECOND, 5); 

     Intent alarmIntent = new Intent(context, AlarmReceiver.class); 
     PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 123, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); 

     AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     alarms.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), intervalMS, recurringDownload); 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d("Alarm", "hello world!"); 
    } 
} 
+0

從哪裏調用方法'setupAlarm'? – FAT

回答

0

當手動殺死它,你把應用程序進入強制停止狀態。這將停止所有接收機和服務,直到您再次手動啓動。這與被操作系統殺死的不一樣。

0

正常進程終止(通過OS)不會取消計劃的AlarmManager事件。所以,在操作系統殺死該進程後,警報仍然可以工作。

如果您手動強制關閉應用程序,則您的警報未註冊。而且,在Android 3.1+上,您必須手動啓動其中一項活動才能再次註冊。 因此,通過手動殺死應用程序,您並不完全模擬操作系統是否會殺死應用程序

0

android:exported="false"表示您不允許您的應用程序從系統接收任何事件。將其更改爲true

一兩件事,一定要打電話setupAlarmContext

從谷歌

的文檔,無論廣播接收器可以從它的應用程序之外的來源接收消息 - 「如果可以,則爲「真」,否則爲「假」。如果是「假」,則廣播接收機可以接收的唯一消息是那些由具有相同用戶ID的相同應用程序或應用程序的組件發送的消息。 默認值取決於廣播接收器是否包含意圖過濾器。沒有任何過濾器意味着它只能由指定其確切類名的Intent對象調用。這意味着接收者僅用於應用程序內部使用(因爲其他人通常不會知道類名)。所以在這種情況下,默認值是「false」。另一方面,至少一個過濾器的存在意味着廣播接收機意在接收由系統或其他應用廣播的意圖,所以默認值是「真」。

該屬性不是限制廣播接收機外部曝光的唯一方法。您還可以使用權限來限制可以發送消息的外部實體(請參閱權限屬性)。

0

所有相應地,但該代碼可能是你有沒有叫你setupAlarm()方法onRecieve()

public class AlarmReceiver extends BroadcastReceiver { 
    public void setupAlarm(Context context, int intervalMS) { 
     this.interval = interval; 

     Calendar updateTime = Calendar.getInstance(); 

     updateTime.add(Calendar.SECOND, 5); 

     Intent alarmIntent = new Intent(context, AlarmReceiver.class); 
     PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 123, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); 

     AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     alarms.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), intervalMS, recurringDownload); 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d("Alarm", "hello world!"); 
     setupAlarm(context,2000);//May be this line is missing. 
    } 
} 
相關問題