Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android使用兩種方式注冊receiver

android使用兩種方式注冊receiver

編輯:關於Android編程

1、

package com.example.myreceiver;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {
	private MyBroadcastReceiver receiver = new MyBroadcastReceiver();
	private IntentFilter filter = new IntentFilter("com.feng.intent");
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@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;
	}
	
	public void start(View view){
		Intent intent = new Intent("com.feng.intent");
		intent.putExtra("name", "wang");
		sendBroadcast(intent);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, filter);
	}
	
	

}

package com.example.myreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyBroadcastReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		System.out.println("good!i've recevied u!");
		Log.e("MyBroadcastReceiver", "good!i've recevied u!");
	}
	
}
這種方式的好處是,使用靈活,可控性高。

另外一種是在mainfest.xml中注冊。這種好處是只要應用程序安裝後,就會一直處於監聽狀態。

      
            
                
            
        



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