Android 发送系统广播与自定义广播

来源:互联网 发布:黑马程序员入学条件 编辑:程序博客网 时间:2024/04/29 03:24
android系统会发送许多系统级别的广播,比如屏幕关闭,电池电量低等广播。同样应用可以发起自定义“由开发者定义的”广播。
(1)发送自定义的广播
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends Activity implements OnClickListener {

    MyReceiver myReceiver;
    IntentFilter intentFilter;
    EditText etReceivedBroadcast;
    Button btnSendBroadcast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
        btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);
        //keep reference to Activity context
        MyApplication myApplication = (MyApplication) this.getApplicationContext();
        myApplication.mainActivity = this;
        btnSendBroadcast.setOnClickListener(this);
        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter("com.hmkcode.android.USER_ACTION");
    }

    @Override
    protected void onResume() {
        super.onResume();
//第一种注册方式(非常驻型广播 当应用程序结束了,广播自然就没有了,比如你在activity中的onCreate或者onResume中注册广播接收器
   // 在onDestory中卸载广播接收器。这样你的广播接收器就一个非常驻型的了。这种也叫动态注册。)        registerReceiver(myReceiver, intentFilter);    }    @Override    protected void onPause() {        super.onPause();        unregisterReceiver(myReceiver);    }    @Override    public void onClick(View view) {        Intent intnet = new Intent("com.hmkcode.android.USER_ACTION");        sendBroadcast(intnet);    }}
第二种注册方式
AndroidManifast.xml进行注册(常驻型广播,当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接受到,
  他的注册方式就是在你的应用程序中的AndroidManifast.xml进行注册。通常说这种方式是静态注册
     <receiver android:name="com.hmkcode.android.MyReceiver" >
     <intent-filter>
           <action android:name="com.hmkcode.android.USER_ACTION" />
     </intent-filter>
</receiver>
(2)发送系统广播
         发送系统广播比如电池电量低的广播Intent.ACTION_BATTERY_LOW;是不用调用sendBroadcast方法,系统会自己发送
总结:系统广播是系统自己监测发送的,自定义广播要手动调用sendBroadcast方法来发送广播

0 0
原创粉丝点击