在code里面注册,只有你的Activity或service处于当前运行的状态才能接受到消息,当Activity或service不处于活的状态,则是接不到消息的。而在xml里面注册的话,那样不管是否处于活的状态都可以接收到消息的.
code:
适用于更新UI,内部使用
- public class Android_TestReceiver_registerInCodeActivity extends Activity implements OnClickListener{
-
private Button registerBtn = null;
-
private Button unRegisterBtn = null;
-
private MySMSReceiver myreceiver = null;
-
private IntentFilter ifilter = null;
-
/** Called when the activity is first created. */
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
-
registerBtn = (Button)findViewById(R.id.registerBtn);
-
unRegisterBtn = (Button)findViewById(R.id.unRegisterBtn);
-
-
registerBtn.setOnClickListener(this);
-
unRegisterBtn.setOnClickListener(this);
-
-
myreceiver = new MySMSReceiver();
-
ifilter = new IntentFilter();
-
ifilter.addAction("android.provider.Telephony.SMS_RECEIVED");
-
-
-
}
-
@Override
-
public void onClick(View v) {
-
//register
-
if(v.getId() == R.id.registerBtn){
-
registerReceiver(myreceiver, ifilter);
-
}
-
-
//unRegister
-
if(v.getId() == R.id.unRegisterBtn){
-
unregisterReceiver(myreceiver);
-
}
-
-
}
-
-
}
XML:
全局的,服务,监听其他应用
- <receiver android:name=".MyReceiver">
-
<intent-filter>
-
<action android:name="android.intent.action.EDIT"/>
-
</intent-filter>
-
</receiver>
阅读(3872) | 评论(0) | 转发(0) |