简体   繁体   中英

How to start an activity from intent using broadcast?

I am using the code to call an intent in Android

Intent intent = new Intent();
String PACKAGE_NAME="com...."
intent.setPackage(PACKAGE_NAME);
intent.setAction(Intent.ACTION_VOICE_COMMAND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
getApplication().startActivity(intent);

Unfortunately, in some case, I do not know the PACKAGE_NAME. So, another method is using broadcast. How can I use it? Thanks all

You cant call Activity directly if you dont know package and name of that Activity.

Since you dont know package and Activity name you can only ask OS to show all possible variants for your Intent Action. In most cases user click "always open this app for this action" what means that you will directly open another app.

So in your case your code should looks like

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VOICE_COMMAND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//dont forget to check if user has at least one application for your Intent Action
if (intent.resolveActivity(getPackageManager()) != null) {
    context.startActivity(intent);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM