Android TimeZone侦听器/接收器 - 未达到MainActivity

时间:2017-02-26 15:10:07

标签: java android timezone broadcastreceiver listener

目标:让Android自动检测时区(TZ)在课堂上发生变化,让MainActivity接收新的TZ。

当前:清单设置,类接收TZ(参见下面的第2项,Log.E在我在手机上更改TZ后显示新的TZ),但是MainActivity / onTZChanged没有接收到新的TZ而根本没有被调用。

问题:如何让MainActivity从班级接收新的TZ?

CODE:

1 - 清单

<receiver
    android:name=".TZChangeReceiver"
    android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.TIMEZONE_CHANGED" />
    </intent-filter>
</receiver>

2 - 班级

public class TZChangeReceiver extends BroadcastReceiver {

    public static TZChangeReceiverListener TZChangeReceiverListener;
    public TZChangeReceiver() {
        super();
    }
    @Override
    public void onReceive(Context context, Intent arg1) {
        String localTZ = TimeZone.getDefault().getID();
        Log.e (" tzchg ", " got it " + localTZ);
        if (TZChangeReceiverListener != null) {
            TZChangeReceiverListener.onTZChanged(localTZ);
        }
    }
    public static String isConnected() {
        String tzToken= TimeZone.getDefault().getID();
        return tzToken ;
    }
    public interface TZChangeReceiverListener {
        void onTZChanged (String isConnected);
    }
}

3 - MainActivity

public class MainActivity extends AppCompatActivity implements  TZChangeReceiver.TZChangeReceiverListener {

...other code...

    @Override
    public void onTZChanged(String isConnected) {
        isConnected = TZChangeReceiver.isConnected();
        Log.e(" TZ", " isConnected " + isConnected);
    }

1 个答案:

答案 0 :(得分:0)

我修好了。我在MainActivity中缺少以下内容

MyApplication.getInstance().setTZChangeListener(this);

,这是在MyApplication中:

public void setTZChangeListener(TZChangeReceiver.TZChangeReceiverListener listener) {
//Log.e(geotime + " MyApp: ","SetConnListener");
TZChangeReceiver.TZChangeReceiverListener = listener;