public class MyReceiver extends BroadcastReceiver{
public final static String TAG = "MyReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "------onReceive------");
}
}
2. 注册我把它写到onResume里面
@Override
protected void onResume() {
super.onResume();
myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION); //ACTION是自己定义的一个成员变量
LocalBroadcastManager.getInstance(MainActivity.this).registerReceiver(myReceiver, filter);
}
Android 中那些零碎的知识点
1 IntentService
IntentService
是Service
的子类,用来处理同步的请求。在IntentService
中会开一个工作线程来处理请求。我们可以通过类似于启动Service
的方来来启动一个IntentService
,IntentService
每创建一次,就会新开启一个工作线程来执行请求。执行完一个intent请求对应的工作后,如果没有新的请求到达,则自动停止IntentService
, 否则会执行下一个请求。所有需要在后台运行的逻辑我们需要写在onHandleIntent
方法中。感觉网上有些博客没说得太清楚,这里自己写个Demo, 加深一下印象来看这么一段代码:
MyIntentService
调用者
假设这个代码是当用户点击一个按钮后执行的。
运行后发现
在这个例子通过观察线程id,发现虽然启动了两次这个
IntentService
,但IntentService
只创建了一次。如果我们将调用的代码改成
同样假设这个代码是当用户点击一个按钮时执行。若用户连续点击这个按钮两次,运行结果发现
在这个例子中,会发现,当
IntentService
处理完一个请求后,确实会将自己销毁。若此下一个请求来了,会再重新创建一个。所以发现两次的thread id不一样。IntentService和Service一个重大的差别是在于,IntentService是会开一个工作线程来处理作务,而Service不会,因此Service中不能执行非常耗时的操作,否则会抛异常。下面便是一种验证方式:
2 PendingIntent
PendingIntent
是对Intent
的一个包装,用来处理未来发生的事。PendingIntent
中会保存当前app的Context, 即使当前app已经停止了,仍然可以通过PendingIntent
中的Context
来执行Intent
,通常与AlarmManager
和NotificationManager
在一起使用。这里有一个示例:3 输入字符转换
之前有这么一个需求,某个
EditText
中接收的英文字母只能是大写的。当看到这个需求,我们的第一反应是设对这个EditText
设置其键盘弹出属性android:inputType="textCapCharacters"
。但是既使这样,用户是可以切换到小写模式下。当然或许我们还可以尝试其它的属性,但是想要统一各种机子上输入法的控制是比较难的,确实有些机子的输入法被产商弄得很奇葩,不受你的控制。我们可以用以下这种方式,自动将其转为大写的样式。定义一个Util类
调用处
4 LocalBroadcastManager
在Android中,对于大部分app而言,发送广播时,只希望广播被自己app内部的receiver监听到,此时我们可以采用LocalBroadcastManager发送广播,安全性高,效率也高。 具体使用: 1. 写一个BroadcastReceiver, 和通常写法一样
2. 注册我把它写到onResume里面
3. 解注册
4. 发广播