Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android廣播接收器Broadcast Receiver-android學習之旅

Android廣播接收器Broadcast Receiver-android學習之旅

編輯:關於Android編程

首先繼承BroadcastReceiver類,並在manifest中注冊

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        throw new UnsupportedOperationException(Not yet implemented);

    }
}

在mainifest中注冊


        

動態注冊和取消廣播接收器

上代碼:
Receiver部分:

public class MyReceiver extends BroadcastReceiver {
    public static final String ACTION = peng.liu.testview.intent.action.MyReceiver;
    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println(intent.getStringExtra(data)+hello);
    }
}

主類部分:

public class MainActivity extends Activity implements View.OnClickListener{
    private MyReceiver receiver = null;
    private Button send,reg,unReg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.send).setOnClickListener(this);
        findViewById(R.id.reg).setOnClickListener(this);
        findViewById(R.id.unReg).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send:
                Intent intent = new Intent(MyReceiver.ACTION);
                intent.putExtra(data,jiekxueyuan);
                sendBroadcast(intent);
                break;
            case R.id.reg:
                if (receiver == null){
                    receiver = new MyReceiver();
                    registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION));
                }
                break;
            case R.id.unReg:
                if (receiver != null){
                    unregisterReceiver(receiver);
                    receiver = null;
                }
                break;

        }
    }
}

布局代碼:

廣播的優先級

這次我們在manifest中靜態注冊

 
        

android:priority:用於設置優先級,數字越大,優先級越高。

高優先級的終端廣播

//發送部分注意是發送sendOrderedBroadcast(intent,null);
Intent intent = new Intent(MyReceiver.ACTION);
                intent.putExtra(data,jiekxueyuan);
                sendOrderedBroadcast(intent,null);

接收部分

public class MyReceiver2 extends BroadcastReceiver {
    public MyReceiver2() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println(intent.getStringExtra(data));
        //這一戶用於中斷後面的低優先級的接受
        abortBroadcast();
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved