BrocastReceiver在code与在xml里面注册的区别

曾经在看过BroadcastReceiver在code与xml的注册的区别:在code里面注册,只有你的Activity或service处于当前运行的状态才能接受到消息,当Activity或service不处于活的状态,则是接不到消息的。而在xml里面注册的话,那样不管是否处于活的状态都可以接收到消息的。可昨天我在接受usb disconnected的消息时,我却犯错了。我在代码里面注册,而我的activity在插上usb时已经进入onpause状态了,当拔掉usb我的activity是不可能接收到usb disconnected消息的。

下面提供两种注册usb BroadcastReceiver的code:
1,在代码里面注册:
private IntentFilter umsFilter;
private BroadcastReceiver mUMSReceiver = null;
umsFilter = new IntentFilter(Intent.ACTION_UMS_CONNECTED);
		umsFilter.addAction(Intent.ACTION_UMS_DISCONNECTED);
		mUMSReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				String action = intent.getAction();
				System.out.println("mUMSReceiver action"+action);
				if (action.equals(Intent.ACTION_UMS_CONNECTED)) {

					//your code

				} else if (action.equals(Intent.ACTION_UMS_DISCONNECTED)) {
					
//your code

				}
			}

		};

//注册
registerReceiver(mUMSReceiver, umsFilter);

//取消注册
unregisterReceiver(mUMSReceiver);



2,xml里面注册

//USBReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class USBReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context arg0, Intent intent) {
		// TODO Auto-generated method stub
		String action = intent.getAction();
		System.out.println("mUMSReceiver action"+action);
		 if (action.equals(Intent.ACTION_UMS_DISCONNECTED)) {
			

		}

	}

}


//manifest.xml
<receiver android:name = ".USBReceiver">
			<intent-filter>
				
				<action android:name="android.intent.action.UMS_DISCONNECTED" />
			</intent-filter>
		</receiver>

你可能感兴趣的:(android,xml)