当前位置: 代码迷 >> Android >> Android BroadcastReceiver 应用
  详细解决方案

Android BroadcastReceiver 应用

热度:123   发布时间:2016-05-01 14:51:37.0
Android BroadcastReceiver 运用

--------------------------------------------Main.xml
package com.example.broad;


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;


public class MainActivity extends
Activity {


@Override
public void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1)
.setOnClickListener(
new OnClickListener() {


public void onClick(
View v) {
// TODO Auto-generated method stub
// Intent intent = new Intent("com.example.broad.broadcast");在MANIFEST配置中加上broadcst
//发送相同的频率与接收.
Intent intent = new Intent(
"com.example.broad.broadcast");
intent.putExtra(
"CONTENT",
"This is broadcast demo");


sendBroadcast(intent);


}
});
}


@Override
public boolean onCreateOptionsMenu(
Menu menu) {
getMenuInflater().inflate(
R.menu.activity_main,
menu);
return true;
}
}


----------------------------------------------ValidateReceiver .java
package com.example.broad;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


public class ValidateReceiver extends BroadcastReceiver {


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


Log.v("ValidateReceiver",
intent.getStringExtra("CONTENT"));

}


}


---------------Manifert.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broad"
    android:versionCode="1"
    android:versionName="1.0" >


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


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <receiver android:name=".ValidateReceiver" >
            <intent-filter>
                <action android:name="com.example.broad.broadcast" />
            </intent-filter>
        </receiver>
      
    </application>


</manifest>

  相关解决方案