Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Studio開發基礎之動態注冊與注銷BroadcastReceiver

Android Studio開發基礎之動態注冊與注銷BroadcastReceiver

編輯:關於Android編程

1、New→Other→BroadcastReceiver

 

package com.example.lhb.startservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }
    public static final String ACTION=com.example.lhb.startservice.intent.action.MyReceiver;//約定俗成,包名+intent.action+MyReceiver
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println(接收到了消息:+intent.getStringExtra(data));
        throw new UnsupportedOperationException(Not yet implemented);
    }
}

2、主程序
package com.example.lhb.startservice;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends Activity implements View.OnClickListener {
    private EditText inputText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    private MyReceiver receiver=null;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnSendMsg:
                Intent intent=new Intent(MyReceiver.ACTION);//隱式傳遞
                intent.putExtra(data,GeoStorm);
                break;
            case R.id.btnReg:
                if(receiver==null){
                    receiver=new MyReceiver();
                    registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION));
                }
                break;
            case R.id.btnUnReg:
                if(receiver!=null) {
                    unregisterReceiver(receiver);
                    receiver = null;
                }
                break;
        }
    }
}
注:只有注冊了接收器後才能發送與接收到消息。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved