0

私はSMSリスナー、以下のコードで作業しています:

public class SMSReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        EventEntry entry = ((MyApplication)context.getApplicationContext()).getCurrent();
        System.out.println("Received message: " + smsMessage[0].getMessageBody() + " - SILENCE IS " + ((entry != null) ? "ON" : "OFF"));
    }
}

そして AndroidManifest への次の変更

<application
    android:name="MyApplication" ...

コードの別の部分 (AlarmManager の BroadcastReceiver 内) では、

public void onReceive(Context context, Intent intent) {
    ((MyApplication).context.getApplicationContext()).setCurrent("TESTING");
}

ただし、アプリケーションを実行してサンプル テキストを送信すると、次のデバッグ メッセージが表示されます。

09-15 15:07:30.974: I/System.out(21625): DEBUG!!!!!! Setting current event to TESTING
09-15 15:07:54.399: I/System.out(21605): DEBUG!!!!!! Getting current event: null

アプリケーション コンテキストが同期していない理由はありますか?

ありがとう!

4

2 に答える 2

0

これの1つの代替ソリューションを提供できます。MyApplicationクラスのonCreate()メソッドをオーバーライドできます。

class MyApplication extends Application {
private static MyApplication singleTon;

public MyApplication getInstance(){
return singleTon;
}

@Override
public void onCreate() {
singleTon = this;
}


...... Here your remaining code....

}

これで、このクラスのインスタンスにアクセスして、getApplicationContex();を呼び出すことができます。

 (MyApplication.getInstance().getapplicationContext()).getCurrent();

それがあなたに役立つことを願っています...:)

于 2012-09-15T20:46:11.067 に答える
0

システムがメモリ不足に直面している場合、アプリケーションはいつでも強制終了できます。したがって、静的変数またはシングルトンは再初期化されます。多分それがそれがnullである理由です。

アプリケーションクラスに保存する代わりに、SharedPreferencesを使用する必要があります

于 2012-09-15T20:47:27.193 に答える