SingleBroadcast.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class SingleBroadcast extends Activity { private static final String CUSTOM_INTENT = "course.examples.BroadcastReceiver.show_toast"; private final IntentFilter intentFilter = new IntentFilter(CUSTOM_INTENT); private final Receiver receiver = new Receiver(); private LocalBroadcastManager mBroadcastMgr; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBroadcastMgr = LocalBroadcastManager .getInstance(getApplicationContext()); mBroadcastMgr.registerReceiver(receiver, intentFilter); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBroadcastMgr.sendBroadcast(new Intent(CUSTOM_INTENT)); } }); } @Override protected void onDestroy() { mBroadcastMgr.unregisterReceiver(receiver); super.onDestroy(); } } |
Receiver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Vibrator; import android.util.Log; import android.widget.Toast; public class Receiver extends BroadcastReceiver { private final String TAG = "Receiver"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "INTENT RECEIVED"); Vibrator v = (Vibrator) context .getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(500); Toast.makeText(context, "INTENT RECEIVED by Receiver", Toast.LENGTH_LONG).show(); } } |
main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="150dip" android:text="@string/broadcast_intent_string" android:textSize="24sp" > </Button> </LinearLayout> |