Broadcast - exemplo completo

Top  Previous  Next

Emissor

Envia a mensagem (Broadcast) para o Android

EmissorBroadcastActivity.java

package com.emissor;

 

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 EmissorBroadcastActivity extends Activity implements OnClickListener {

   

  @Override

  public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

       

       Button button1 = (Button) findViewById(R.id.button1);

       button1.setOnClickListener(this);

   }

 

 public void onClick(View arg0) {

         sendBroadcast(new Intent("FAZER_ALGO"));

 }

}

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="fill_parent"

  android:layout_height="fill_parent"

  android:orientation="vertical" >

 

  <Button

      android:id="@+id/button1"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="Clique" />

 

</LinearLayout>

 


Receptor

Recepciona mensagem e mostra um toast

manifest

 

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

  package="com.receiverdemo"

  android:versionCode="1"

  android:versionName="1.0" >

 

  <uses-sdk android:minSdkVersion="7" />

 

  <application

      android:icon="@drawable/ic_launcher"

      android:label="@string/app_name" >

      <receiver android:name=".Receptor" >

          <intent-filter>

              <action android:name="FAZER_ALGO" />

              <category android:name="android.intent.category.DEFAULT" />

          </intent-filter>

      </receiver>

  </application>

 

</manifest>

 

Receptor.java

 

package com.receiverdemo;

 

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

 

public class Receptor extends BroadcastReceiver {

 

 @Override

 public void onReceive(Context c, Intent intent) {

         Toast.makeText(c, "Recebi!", Toast.LENGTH_SHORT).show();

 }

}