zoukankan      html  css  js  c++  java
  • 安卓开发之无序广播

    package com.lidaochen.test001;
    
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        // 点击按钮发送一条无序广播
        public void click(View v)
        {
            Intent intent = new Intent();
            intent.setAction("com.lidaochen.custom");
            intent.putExtra("name", "新闻联播每天晚上7点准时开播!");
            // 发送无序广播
            sendBroadcast(intent);
        }
    }
    package com.lidaochen.test002;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    import android.widget.Toast;
    
    public class ReceiveCustomReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO: This method is called when the BroadcastReceiver is receiving
            // an Intent broadcast.
            // 终止广播 (这里终止了广播,当前广播接受者依然可以收到数据)
            abortBroadcast();
            // 接收无序广播 携带的数据
            String content = intent.getStringExtra("name");
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
            Log.e("收到数据:", content);
        }
    }
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.lidaochen.test002">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <receiver
                android:name=".ReceiveCustomReceiver"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="com.lidaochen.custom"></action>
                </intent-filter>
            </receiver>
        </application>
    
    </manifest>
  • 相关阅读:
    经典多线程问题(四)-轮流打印字母和数字
    经典多线程问题 (一)-多线程售票
    买卖股票的最佳时机 II
    最长递增(严格递增)子序列-可以不连续
    环形链表 II
    最小栈
    买卖股票的最佳时机
    二叉树的层序遍历
    字符串相加
    最大子序和
  • 原文地址:https://www.cnblogs.com/duxie/p/11027257.html
Copyright © 2011-2022 走看看