本文主要是介绍Android BroadcastRecevier广播消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码注册Receiver
@Overrideprotected void onCreate(Bundle savedInstanceState) {IntentFilter intentFilter = new IntentFilter();intentFilter.addAction("");MyBroadcast myBroadcast = new MyBroadcast();registerReceiver(myBroadcast, intentFilter);}
AndroidManifest.xml
<receiver android:name=".MyBroadcast"><intent-filter><action android:name="shortcut.song.com.myapplication.MY_BROADCAST"/></intent-filter></receiver>
MyBroadcast .java
package shortcut.song.com.myapplication;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;/*** Created by Administrator on 2017/8/16 0016.*/public class MyBroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context, "接收到的Intent Action为:"+intent.getAction() +" \n 消息内容:"+intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="shortcut.song.com.myapplication.BroadcastTestActivity"><Button
android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="SendBroadcast"android:onClick="sendBroadCast"/>
</LinearLayout>
package shortcut.song.com.myapplication;import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;public class BroadcastTestActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_broadcast_test);}public void sendBroadCast(View v) {Intent intent = new Intent();intent.setAction("shortcut.song.com.myapplication.MY_BROADCAST");intent.putExtra("msg", "简单的消息");//发送广播sendBroadcast(intent);}}
这篇关于Android BroadcastRecevier广播消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!