0

我有一個應用程序,對我來說檢測時間更改很重要。到目前爲止,我已經與適當的意圖過濾器接收這樣的:即使應用關閉,如何獲取時間更改廣播

<receiver 
    android:name=".MyReceiver" 
    android:enabled="true" 
    android:exported="true"> 
    <intent-filter> 
    <action android:name="android.intent.action.TIME_SET" /> 
    <action android:name="android.intent.action.ACTION_TIME_CHANGED" /> 
    <action android:name="android.intent.action.DATE_CHANGED" /> 
    </intent-filter> 
</receiver> 

,這是我的接收器:

public class MyReceiver extends BroadcastReceiver { 
    public MyReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     SharedPreferences.Editor spe =PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()).edit(); 
     spe.putLong("UFCount", 1)); 
     spe.putLong("FCount", 1)); 
     spe.commit(); 
     Toast.makeText(context.getApplicationContext(), "Your job is being done!!", Toast.LENGTH_LONG).show(); 
    } 
} 

這個接收器只有當應用程序被打開\在最後臺運行。即使應用程序已關閉,我如何使此接收器工作?

+0

您可以點擊此鏈接[http://stackoverflow.com/a/16824692/4049612](http://stackoverflow.com/a/16824692/4049612) – Krishna

+0

@Krishna我不覺得有一個良好的服務始終運行。我不認爲它是這樣做的最佳方式 – hadi

回答

0

由於應用程序已關閉,因此沒有用於顯示Toast的UI(即無活動)。此時,Logcat應該有一個例外。您可能還會在顯示Toast之前添加logcat跟蹤,例如Log.d("MyReceiver", "in onCreate()");,即使應用已關閉,您也應該看到它。

而不是顯示一個吐司,你可以發送一個local notification,這是允許的,因爲它不需要從你的應用程序的活動。

+0

我確實使用了日誌,但它不起作用。我搜索了日誌,它沒有顯示,因此接收器沒有觸發 – hadi

+0

如果你正在從Android Studio看logcat,你可以嘗試並禁用logcat過濾器,看看你得到了什麼? AS有時會遇到來自封閉應用程序的痕跡 – Lolo

+0

是的,我也是這麼做的。仍然沒有顯示出來。我不知道'android.intent.action.TIME_SET'行動是否有標誌打開封閉的應用程序組件?! – hadi

相關問題