BroadcastReceiver Example in Android
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="BroadCast" />
</RelativeLayout>
MyBroadcast.java
package
com.swamys.broadcastreceiver;
import
android.content.BroadcastReceiver;
import
android.content.Context;
import
android.content.Intent;
import android.widget.Toast;
public class MyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context
context, Intent intent) {
Toast.makeText(context,
"onReceive()
called", Toast.LENGTH_LONG).show();
}
}
MainActivity.java
package com.swamys.broadcastreceiver;
import
android.app.Activity;
import
android.content.Intent;
import android.os.Bundle;
import android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent
intent = new Intent(getApplicationContext(),
MyBroadcast.class);
sendBroadcast(intent);
}
});
}
}
Manifest.xml
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.swamys.broadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.swamys.broadcastreceiver.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>
<receiver android:name="com.swamys.broadcastreceiver.MyBroadcast"
>
</receiver>
</application>
</manifest>
No comments:
Post a Comment