zoukankan      html  css  js  c++  java
  • Android中创建一个BroadcastReceiver

    首先创建一个java类继承BroadcastReceiver类

    package com.example.service;
    
    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 context, Intent intent) {
            // TODO: This method is called when the BroadcastReceiver is receiving
            // an Intent broadcast.
            String msg=intent.getStringExtra("msg");//获得广播信息
            Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    
    
        }
    }
    

     Mainactivity中添加如下语句进行数据的广播  Intent it=new Intent();

                it.setAction("android.intent.action.EDIT");//自定义地址
                //it.setComponent(new ComponentName("com.example.service", //此段内容用于Android8.0无法接收广播的情况参数1是自定义广播的包名,
    // "com.example.service.MyBroadcastReceiver"));//
    参数2是自定义广播的路径
    it.putExtra("msg","广播已接收"); MainActivity.this.sendBroadcast(it); 

      在AndroidMainfest.xml中注册,在<application></application>中添加

     <receiver
                android:name=".MyBroadcastReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.EDIT"/>
                </intent-filter>
            </receiver>
    

      

  • 相关阅读:
    LeetCode 38. 外观数列
    LeetCode 33. 搜索旋转排序数组
    LeetCode 31. 下一个排列
    LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置
    LeetCode 29. 两数相除
    LeetCode 22. 括号生成
    LeetCode 1. 两数之和
    LeetCode 17. 电话号码的字母组合
    LeetCode 18. 四数之和
    LeetCode 16. 最接近的三数之和
  • 原文地址:https://www.cnblogs.com/liuleliu/p/12266147.html
Copyright © 2011-2022 走看看