Wednesday, 24 April 2013

BroadCastReceiver Demo 1

Demo:

1) MainActivity.java:

package com.venky.broadcastreceiverdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

      private BroadcastReceiver bc = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                  // TODO Auto-generated method stub

                  int batteryStatus = intent.getIntExtra("level", 0);

                  TextView tv = (TextView) findViewById(R.id.textView1);
                  tv.setText("Battery Status => " + batteryStatus + " %");

                  ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
                  pb.setProgress(batteryStatus);
            }
      };

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            registerReceiver(bc, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      }

}


2) main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#5F04B4"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:layout_gravity="center"
        android:layout_marginTop="70dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp" />

</LinearLayout>


 3) Download this Project Click Here

No comments:

Post a Comment