原文地址为: android使用两种方式注册receiver

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{@Overridepublic void onReceive(Context arg0, Intent arg1) {System.out.println("good!i've recevied u!");Log.e("MyBroadcastReceiver", "good!i've recevied u!");}}
这种方式的好处是,使用灵活,可控性高。

另外一种是在mainfest.xml中注册。这种好处是只要应用程序安装后,就会一直处于监听状态。

      







转载请注明本文地址: android使用两种方式注册receiver

更多相关文章

  1. Android(安卓)SqlLiter使用
  2. API 23及之后版本关于用android studio 中LocationManager的方法
  3. 【Android】Http请求
  4. Android中对话框的使用
  5. android 应用选择器的使用
  6. Android下按扭的使用方法
  7. 箭头函数的基础使用
  8. NPM 和webpack 的基础使用
  9. Python list sort方法的具体使用

随机推荐

  1. 你不知道的Android着色器/渲染器
  2. 第一章:初入Android大门(不同的Activity
  3. Android百度地图将经纬度转换为地址信息
  4. Android(安卓)Canvas练习(8)自已绘环形图
  5. 在ubuntu操作系统下配置android开发环境
  6. Android(安卓)Studio “Cannot resolve s
  7. android中查找某个Activity中的view
  8. Bluetooth in Android(安卓)4.2 and 4.3(
  9. 修改Android中AVD的目录
  10. Android(安卓)数据显示在屏幕上