Friday 14 June 2013

Android: Toast After Certain Time uisng AlarmManager

 MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    final static private long ONE_SECOND = 1000;
    final static private long TWENTY_SECONDS = ONE_SECOND * 20;
    PendingIntent pi;
    BroadcastReceiver br;
    AlarmManager am;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setup();
        findViewById(R.id.the_button).setOnClickListener(this);

    }

    private void setup() {
        br = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent i) {
                Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();

            }
        };
        registerReceiver(br, new IntentFilter("com.example.scheduleevent"));
        pi = PendingIntent.getBroadcast(this, 0, new Intent(
                "com.example.scheduleevent"), 0);
        am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
    }

    @Override
    public void onClick(View v) {
        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + TWENTY_SECONDS, pi);

    }

    @Override
    protected void onDestroy() {
        am.cancel(pi);
        unregisterReceiver(br);
        super.onDestroy();
    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alarm Example" />
    <Button
        android:id="@+id/the_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set"/>
</LinearLayout>










No comments:

Post a Comment