1. 程式人生 > >Android簡單實現BroadCastReceiver廣播機制

Android簡單實現BroadCastReceiver廣播機制

Android中廣播的作用是非常明顯的,當我們收到一條資訊,可能我們的應用需要處理一些資料,可能我們開機,我們的應用也需要處理一些資料,這裡都用到了廣播機制,這裡簡單的實現了一個自定義廣播,看例項: MyBroadcastReceiver.java
package com.example.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "onReceive", Toast.LENGTH_SHORT).show();
}

}
MainActivity.java
package com.example.broadcastreceiver;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
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 btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction("justsoso");
sendBroadcast(intent);
}});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.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=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="justsoso" >
</action>
</intent-filter>
</receiver>
</application>

</manifest>

當點選按鈕以後,就會返回廣播觸發的事件了