目标:在类中具有Android Auto-Detect TigeZone(TZ)的变化,并使MainActivity接收新的TZ。
电流:清单是设置,类接收TZ(请参见下面的第2项,log.e在我通过电话更改TZ后显示新的TZ),但是MainAttivity/ontzchanged未接收新的TZ并且根本没有被调用。
问题:如何获得从课堂上接收新TZ的主要目的?
代码:
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-主进
public class MainActivity extends AppCompatActivity implements TZChangeReceiver.TZChangeReceiverListener {
...other code...
@Override
public void onTZChanged(String isConnected) {
isConnected = TZChangeReceiver.isConnected();
Log.e(" TZ", " isConnected " + isConnected);
}
我修复了它。我错过了以下内容
MyApplication.getInstance().setTZChangeListener(this);
这是在myapplication中:
public void setTZChangeListener(TZChangeReceiver.TZChangeReceiverListener listener) {
//Log.e(geotime + " MyApp: ","SetConnListener");
TZChangeReceiver.TZChangeReceiverListener = listener;