nsnotificationCenterに相当するAndroid
-
08-10-2019 - |
質問
iPhoneアプリケーションをAndroidに移植する過程で、アプリ内で通信する最良の方法を探しています。意図が進むべき方法のようです、これは最良の(唯一の)オプションですか? nsuserdefaultsは、パフォーマンスとコーディングの両方で行われる意図よりもはるかに軽量のようです。
また、状態向けのアプリケーションサブクラスを追加する必要がありますが、別のアクティビティにイベントを認識する必要があります。
解決
あなたはこれを試すことができます: http://developer.android.com/reference/java/util/observer.html
他のヒント
私が見つけた最高の同等物はです LocalBroadCastManager これはの一部です Androidサポートパッケージ.
LocalBroadCastManagerのドキュメントから:
プロセス内のローカルオブジェクトに登録し、意図のブロードキャストを送信するヘルパー。これには、SendBroadcast(Intent)でグローバル放送を送信する上で多くの利点があります。
- 放送しているデータはアプリを離れないことを知っているので、プライベートデータの漏れを心配する必要はありません。
- 他のアプリケーションがこれらのブロードキャストをアプリに送信することは不可能であるため、悪用できるセキュリティホールがあることを心配する必要はありません。
- システムを介してグローバルブロードキャストを送信するよりも効率的です。
これを使用するとき、あなたはそれを言うことができます Intent
と同等です NSNotification
. 。これが例です:
Receiveractivity.java
名前付きイベントの通知を見るアクティビティ "custom-event-name"
.
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// This is just like [[NSNotificationCenter defaultCenter] addObserver:...]
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
// This is somewhat like [[NSNotificationCenter defaultCenter] removeObserver:name:object:]
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
senderActivity.java
通知を送信/ブロードキャストする2番目のアクティビティ。
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Every time a button is clicked, we want to broadcast a notification.
findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}
// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
上記のコードを使用すると、ボタンがたびに R.id.button_send
クリックされ、意図がブロードキャストされ、 mMessageReceiver
の ReceiverActivity
.
デバッグ出力は次のようになります。
01-16 10:35:42.413: D/sender(356): Broadcasting message
01-16 10:35:42.421: D/receiver(356): Got message: This is my message!
@shikiの回答に似たものですが、iOS開発者と通知センターの角度からです。
まず、ある種の通知センターサービスを作成します。
public class NotificationCenter {
public static void addObserver(Context context, NotificationType notification, BroadcastReceiver responseHandler) {
LocalBroadcastManager.getInstance(context).registerReceiver(responseHandler, new IntentFilter(notification.name()));
}
public static void removeObserver(Context context, BroadcastReceiver responseHandler) {
LocalBroadcastManager.getInstance(context).unregisterReceiver(responseHandler);
}
public static void postNotification(Context context, NotificationType notification, HashMap<String, String> params) {
Intent intent = new Intent(notification.name());
// insert parameters if needed
for(Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
intent.putExtra(key, value);
}
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
次に、文字列でのコーディングの間違いを確保するために、列挙タイプが必要になります - (notificationType):
public enum NotificationType {
LoginResponse;
// Others
}
アクティビティの場合など、使用法(オブザーバーを追加/削除)です。
public class LoginActivity extends AppCompatActivity{
private BroadcastReceiver loginResponseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// do what you need to do with parameters that you sent with notification
//here is example how to get parameter "isSuccess" that is sent with notification
Boolean result = Boolean.valueOf(intent.getStringExtra("isSuccess"));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//subscribe to notifications listener in onCreate of activity
NotificationCenter.addObserver(this, NotificationType.LoginResponse, loginResponseReceiver);
}
@Override
protected void onDestroy() {
// Don't forget to unsubscribe from notifications listener
NotificationCenter.removeObserver(this, loginResponseReceiver);
super.onDestroy();
}
}
そして、最後に、いくつかのコールバックや休憩サービスなどから通知を通知する方法を投稿する方法が次のとおりです。
public void loginService(final Context context, String username, String password) {
//do some async work, or rest call etc.
//...
//on response, when we want to trigger and send notification that our job is finished
HashMap<String,String> params = new HashMap<String, String>();
params.put("isSuccess", String.valueOf(false));
NotificationCenter.postNotification(context, NotificationType.LoginResponse, params);
}
それだけです、乾杯!
これを使用できます: http://developer.android.com/reference/android/content/broadcastreceiver.html, 、同様の動作を与えます。
Context.RegisterReceiver(BroadCastReceiver、IntentFilter)を介してプログラムでレシーバーを登録でき、Context.SendBroadCast(Intent)を介して送信された意図をキャプチャできます。
ただし、そのアクティビティ(コンテキスト)が一時停止した場合、受信者は通知を取得しないことに注意してください。
Guava libのEventbusの使用は、コンポーネントが互いに明示的に登録することを要求することなく、コンポーネント間のパブリックサブスクライブスタイルの通信のための最も簡単な方法であることがわかりました。
それらのサンプルを参照してください https://code.google.com/p/guava-libraries/wiki/eventbusexplained
// Class is typically registered by the container.
class EventBusChangeRecorder {
@Subscribe public void recordCustomerChange(ChangeEvent e) {
recordChange(e.getChange());
}
// somewhere during initialization
eventBus.register(this);
}
// much later
public void changeCustomer() {
eventBus.post(new ChangeEvent("bla bla") );
}
build.gradleに依存関係を追加することで、このlibをAndroid Studioに追加することができます。
compile 'com.google.guava:guava:17.0'
弱い参照を使用できます。
このようにして、自分でメモリを管理し、あなたが好きなようにオブザーバーを追加して削除することができます。
addobserverがこれらのパラメーターを追加すると、空のインターフェイスに追加するアクティビティからそのコンテキストをキャストし、通知名を追加し、メソッドを呼び出してインターフェイスを実行します。
インターフェイスを実行する方法には、このようなものを渡すデータを返すために実行されるように呼ばれる関数があります
public static interface Themethodtorun {
void run(String notification_name, Object additional_data);
}
空のインターフェイスを使用して参照を呼び出す観察クラスを作成します。また、addobserverで渡されるコンテキストからTheTheTheThodtorunインターフェイスを作成します。
データ構造に観察を追加します。
それを呼び出すには同じ方法ですが、あなたがする必要があるのは、データ構造に特定の通知名を見つけることだけです。TheTheTheThodTorun.run(notification_name、data)を使用します。
これにより、特定の通知名でオブザーバーを作成した場所にコールバックが送信されます。あなたが終わったらそれらを削除することを忘れないでください!
これは、弱い参照のための適切な参照です。
http://learningviacode.blogspot.co.nz/2014/02/weak-references-in-java.html
私はこのコードをGitHubにアップロードする過程にあります。目を開けてください!