我有一个android应用程序。在这里,每当用户更改设备时区时,我都希望事件侦听器通知我。我怎样才能完成它?
用以下意图过滤器注册接收器
filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
filter.addAction(Intent.ACTION_TIME_CHANGED);
并将其注册到活动的OnCreate
public void onCreate() {
super.onCreate();
registerReceiver(receiver, filter);
}
按如下方法创建Broadcast接收器
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
doWorkSon();
}
}
};
并在活动的onDestroy
中注销它:
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
你需要为意图动作ACTION_TIMEZONE_CHANGED创建一个BroadcastReceiver。此处描述BroadcastReceiver
在manifest文件
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.TIMEZONE_CHANGED"/>
</intent-filter>
</receiver>
在myReceiver类中
override fun onReceive(context: Context, intent: Intent) {
var action : String? = intent.action
var timeZone: String? = intent.getStringExtra("time-zone")
Toast.makeText(context,action+timeZone,Toast.LENGTH_LONG).show()