web-dev-qa-db-fra.com

Comment envoyer une action de diffusion personnalisée aux destinataires du manifeste?

MyReceiver.Java

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.i("MyReceiver", "MyAction received!");
    }
}

Dans AndroidManifest.xml (sous la balise application)

<receiver Android:name=".MyReceiver">
    <intent-filter>
        <action Android:name="MyAction" />
    </intent-filter>
</receiver>

MainActivity.Java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendBroadcast(new Intent("MyAction"));
    }
}

La méthode MyReceiver.onReceive n'est jamais déclenchée . Ai-je oublié quelque chose?

7
Yairopro

J'utilise Android 8.

Ensuite, vous devez utiliser une variable Intent explicite, identifiant le destinataire, telle que:

sendBroadcast(new Intent(this, MyReceiver.class).setAction("MyAction"));
9
CommonsWare

Dans Android 8 onwords 

  • Nous devons fournir la classe explicite pour gérer i.e setcomponent param avec action 

Exemple :

  private void triggerBroadCast(String firstFavApp, String secondFavApp) {
        Intent intent = new Intent("FavAppsUpdated");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intent.putExtra("FIRST_FAV_APP", firstFavApp);
        intent.putExtra("SECOND_FAV_APP", secondFavApp);
        intent.setComponent(new
                ComponentName("com.Android.systemui",
                "com.Android.systemui.statusbar.phone.FavAppsChanged"));

        Log.i(TAG, "Trigger Fav Apps" + firstFavApp + " " + secondFavApp);
        favouriteContract.getAppContext().sendBroadcast(intent);
    }

Ci-dessous Android 8

  • Seule une action suffit pour recevoir la diffusion

   void broadCastParkingStates(Context context) {
        Intent intent = new Intent("ReverseCameraStates");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intent.putExtra("PARKING_GUIDE", ReverseCameraPreference.getParkingGuide(context));
        intent.putExtra("PARKING_SENSOR", ReverseCameraPreference.getParkingSensor(context));
        intent.putExtra("TRAJECTORY", ReverseCameraPreference.getTrajectory(context));
        Log.i("BootCompletedReceiver", "Sending Reverse Camera settings states BaordCast");
        Log.i("BootCompletedReceiver", "States Parking:Sensor:Trajectory="
                + intent.getExtras().getBoolean("PARKING_GUIDE")
                + ":" + intent.getExtras().getBoolean("PARKING_SENSOR")
                + ":" + intent.getExtras().getBoolean("TRAJECTORY")
        );
        context.sendBroadcast(intent);
    }
0
Vinayak