Monday, 7 December 2015

Android/SCREEN ON, SCREEN OFF BroadcastReceiver

public class MyApplication extends Application {
    public static final String TAG = "SCREEN";
 
    private BroadcastReceiver scrOnReceiver;
    private BroadcastReceiver scrOffReceiver;
    private IntentFilter scrOnFilter;
    private IntentFilter scrOffFilter;
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        scrOnReceiver = new BroadcastReceiver() { 
            @Override 
            public void onReceive(Context context, Intent intent) { 
                Log.d(TAG, "SCREEN ON"); 
  timer.cancel();
            } 
        };
 
        scrOnFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); 
 
        scrOffReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "SCREEN OFF");
  timer.start();
            }
        };
 
        scrOffFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
 
        registerReceiver(scrOnReceiver, scrOnFilter);
        registerReceiver(scrOffReceiver, scrOffFilter);
    }

//time counting
 CountDownTimer timer = new CountDownTimer(1*60*1000, 1000) {

        public void onTick(long millisUntilFinished) {
           //Some code
         Log.d("timer", "--"+millisUntilFinished);
         
        }

        public void onFinish() {
           //Logout
         Intent intent=new Intent(AppController.this,LoginActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

         Log.d("***********", "logout");
        }
     };
 
    @Override
    public void onTerminate() {
        super.onTerminate();
 
        unregisterReceiver(scrOnReceiver);
        unregisterReceiver(scrOffReceiver);
    }
 
}




<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
   </application>