selfstarter

BroadcastReciver app to app in Android 본문

App/Android

BroadcastReciver app to app in Android

selfstarter 2020. 3. 18. 15:12

BroadcastReciver app to app

  • BroadcastReciver란 Android 시스템 등으로 부터 어떤 이벤트가 발생했을 시 수신등록을 했다면 수신 알람을 받는 기능이다.
  • 그러므로 A와 B 둘 다 같은 폰에 있는 app이어야 한다

BroadcastReciver app to app Example

  • send broadcast app

  • send broadcast to B when I click send button

    public void click(View v) {
      Intent intent = new Intent();
      intent.setAction("com.test.broadcastexample");    // action name
      intent.putExtra("data", "Notice me senpai!");
      getApplicationContext().sendBroadcast(intent);
    }
  • Receive broadcast app

  • AndroidManifest.xml

    <receiver android:name=".MyBroadcastReceiver"
      android:enabled="true"
      android:exported="true">
      <intent-filter>
          <action android:name="com.test.broadcastexample"/>
      </intent-filter>
    </receiver>
  • MainActivity.java

    BroadcastReceiver br = new MyBroadcastReceiver();
    IntentFilter filter = new IntentFilter("com.ahope.broadcastexample");
    this.registerReceiver(br, filter);
  • MyBroadcastReceiver.java

    public class MyBroadcastReceiver extends BroadcastReceiver {
      private static final String TAG = "MyBroadcastReceiver";
      @Override
      public void onReceive(Context context, Intent intent) {
          Toast.makeText(context, intent.getAction(), Toast.LENGTH_LONG).show();
      }
    }
Comments