码迷,mamicode.com
首页 > 移动开发 > 详细

安卓开发之无序广播

时间:2019-06-15 13:36:57      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:The   lidao   extra   cal   prot   app   class   sch   import   

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>

 

安卓开发之无序广播

标签:The   lidao   extra   cal   prot   app   class   sch   import   

原文地址:https://www.cnblogs.com/duxie/p/11027257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!