zoukankan      html  css  js  c++  java
  • Android 广播(Broadcast)简单的学习

    广播事件的流程
    ①注册广播事件:注册方式有两种,一种是静态注册,就是在AndroidManifest.xml文件中定义,注册的广播接收器必须要继承BroadcastReceiver;另一种是动态注册,是在程序中使用Context.registerReceiver注册,注册的广播接收器相当于一个匿名类。两种方式都需要IntentFIlter。
    ②发送广播事件:通过Context.sendBroadcast来发送,由Intent来传递注册时用到的Action。
    ③接收广播事件:当发送的广播被接收器监听到后,会调用它的onReceive()方法,并将包含消息的Intent对象传给它。onReceive中代码的执行时间不要超过5s,否则Android会弹出超时dialog。

    静态注册广播Demo:

    manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.rainwii.client"
        android:versionCode="1"
        android:versionName="1.0"
        android:sharedUserId="com.rainwii.share" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="18" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.rainwii.client.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <receiver 
                android:name="com.rainwii.client.MyBroadcastReceive"
                >
                <intent-filter>
                    <action android:name="ccc"></action>
                 </intent-filter>
            </receiver>
        </application>
    
    </manifest>
    View Code

    MainActivity

    package com.rainwii.client;
    
    import com.rainwii.main.R;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    Button startappbutton;
    String str;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            startappbutton= (Button) findViewById(R.id.button1);
            startappbutton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent();
                    intent.putExtra("msg", "你好,我是一个广播");
                    intent.setAction("ccc");
                    intent.setClass(MainActivity.this, MyBroadcastReceive.class);
                    MainActivity.this.sendBroadcast(intent);
                }
            });
                  
          
        }
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        
    }
    View Code

    MyBroadcastReceive

    package com.rainwii.client;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;
    
    public class MyBroadcastReceive extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
        
            String string=intent.getStringExtra("msg");
            Toast.makeText(context, "广播被收到了!
    "+string, Toast.LENGTH_SHORT).show();
        }
    }
    View Code

    动态注册广播Demo:

            // 注册自定义动态广播消息  
            IntentFilter filter_dynamic = new IntentFilter();  
            filter_dynamic.addAction(DYNAMICACTION);  
            registerReceiver(dynamicReceiver, filter_dynamic);  
            // 注册系统动态广播消息  
            IntentFilter filter_system = new IntentFilter();  
            filter_system.addAction(SYSTEMACTION);  
            registerReceiver(systemReceiver, filter_system);         

    MainActivity

    package com.rainwii.client;
    
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    Button staticbutton,dynamicbutton;
    String str;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
    //        staticbutton= (Button) findViewById(R.id.button1);
            dynamicbutton= (Button) findViewById(R.id.button2);
    //        staticbutton.setOnClickListener(new OnClickListener() {
    //            
    //            @Override
    //            public void onClick(View v) {
    //                // TODO Auto-generated method stub
    //                Intent intent = new Intent();
    //                intent.putExtra("msg", "你好,我是一个静态广播");
    //                intent.setAction("ccc");
    //                //intent.setClass(MainActivity.this, MyBroadcastReceive.class);
    //                MainActivity.this.sendBroadcast(intent);
    //                
    //            }
    //        });
            dynamicbutton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Log.e("MainActivity", "发送自定义动态注册广播消息");  
                    Intent intent = new Intent();  
                    intent.setAction("aaa");  
                    intent.putExtra("msg", "接收动态注册广播成功!");  
                    sendBroadcast(intent);  
                }
            });
                  
          
        }
    
        @Override
        protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            // 注册自定义动态广播消息  
            IntentFilter filter_dynamic = new IntentFilter();  
            filter_dynamic.addAction("aaa");  
            registerReceiver(dynamicReceiver, filter_dynamic);  
           
        }
    
        private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {  
            
            @Override  
            public void onReceive(Context context, Intent intent) {  
                Log.e("MainActivity", "接收自定义动态注册广播消息");  
                if(intent.getAction().equals("aaa")){  
                    String msg = intent.getStringExtra("msg");  
                    Toast.makeText(context, msg, Toast.LENGTH_LONG).show();  
                }  
            }  
        };  
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        
    }
    View Code

    ===============================================================

    需求:如果c应用想通过广播启动d应用的Activity或者服务。

    方法:可以在c应用中启动广播,d应用接收到广播使用startactivity启动页面。

                              作者:xubuhang                出处:http://www.cnblogs.com/xubuhang/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 

     
查看全文
  • 相关阅读:
    Benelux Algorithm Programming Contest 2016 Preliminary K. Translators’ Dinner(思路)
    Benelux Algorithm Programming Contest 2016 Preliminary Target Practice
    Benelux Algorithm Programming Contest 2016 Preliminary I. Rock Band
    Benelux Algorithm Programming Contest 2016 Preliminary A. Block Game
    ICPC Northeastern European Regional Contest 2019 Apprentice Learning Trajectory
    ICPC Northeastern European Regional Contest 2019 Key Storage
    2018 ACM ICPC Asia Regional
    2018 ACM ICPC Asia Regional
    Mybatis入库出现异常后,如何捕捉异常
    优雅停止 SpringBoot 服务,拒绝 kill -9 暴力停止
  • 原文地址:https://www.cnblogs.com/xubuhang/p/4134899.html
  • Copyright © 2011-2022 走看看