2013-10-17 144 views
1

我建立應接收Android的android.intent.action.SCREEN_ON廣播的和做的背景是什麼應用程序。運行將接收SCREEN_ON服務廣播

(即廣播保護,不能被添加到清單中的IntentFilter部分,則需要可通過編程registerReceiver()註冊)

我知道如何啓動服務。我知道如何讓獨立啓動它的活動的(因此它不會與它死了)。真正的問題是:

如何在服務中註冊SCREEN_ON廣播接收器,即使服務由於系統發送廣播而導致RAM數量低而被設備暫時中止,它也會被服務接收到?

回答

1
public class OnBootService extends Service { 

    private static final String TAG = OnBootService.class.getSimpleName(); 
    private PowerButtonReceiver mPowerButtonReceiver = null; 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public int onStartCommand(final Intent intent, final int flags, final int startId) { 

    if (mPowerButtonReceiver==null) { 
     mPowerButtonReceiver = new PowerButtonReceiver(); 
     registerReceiver(mPowerButtonReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); 
    } 
    return Service.START_NOT_STICKY; 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 

    Log.i(TAG,"onCreate()"); 
} 

    // unregister the Receiver when the Service gets stopped (destroyed) 
@Override 
public void onDestroy() { 
    super.onDestroy(); 

    unregisterReceiver(mPowerButtonReceiver); 

    Log.i(TAG, ""+TAG+" stopped: "+ new Date().toString()); 
    } 
} 

編輯:我添加了powerButtonReceiver太:

public class PowerButtonReceiver extends BroadcastReceiver { 

    private static final String TAG = "PowerButtonReceiver"; 

    private int mPowerClickCounter = 0; 
    private boolean inTime = true; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     SharedPreferences sharedPref = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); 

     Boolean bCheck = sharedPref.getBoolean("PowerButtonReceiverState", false); 

     // check if screen is on 
     PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
     Boolean screenOn = pm.isScreenOn(); 
     Log.i(TAG, "Screen is on: " + screenOn.toString()); 
}}  
+0

這是你在找什麼? – bofredo

+0

看起來這應該這樣做,但是如果服務正在重新啓動什麼(例如,由於內存不足)時的廣播系統發送的?將'PowerButtonReceiver'的'的onReceive()'被稱爲靜止? –

+0

,直到你重新啓動設備或明確地停止它的服務應該是積極的。第二種選擇:您可以使服務變得粘稠,然後只有在您明確停止服務時纔會停止。 – bofredo