某些時候你想要知道某個APP是否有注冊了一個明確的intent,比如說你想要檢查某個receiver是否存在,然後根據是否存在來這個receiver來在你的AP裡面enable某些功能。我們可以通過PackageManager來check它。
code
public boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfo.size() > 0) {
return true;
}
return false;
}
干貨
一般APP的manifest裡面要設置為launcher的activity總是要設置intent-filter:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
可以通過queryIntentActivities來獲得有哪些launcher:
private void loadApps() {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
}
我們可以在自己的app上用一個gridview顯示出當前手機有哪些app:
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MyHome extends Activity
{
GridView mGrid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadApps();
setContentView(R.layout.main);
mGrid = (GridView) findViewById(R.id.apps_list);
mGrid.setAdapter(new AppsAdapter());
}
private List<ResolveInfo> mApps;
private void loadApps() {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
}
public class AppsAdapter extends BaseAdapter
{
public AppsAdapter() { }
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i;
if (convertView == null) {
i = new ImageView(MyHome.this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new GridView.LayoutParams(50, 50));
} else {
i = (ImageView) convertView;
}
ResolveInfo info = mApps.get(position);
i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
return i;
}
public final int getCount() {
return mApps.size();
}
public final Object getItem(int position) {
return mApps.get(position);
}
public final long getItemId(int position) {
return position;
}
}
}
可以設置點擊監聽器去開啟app:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
ResolveInfo info = mApps.get(position);
//該應用的包名
String pkg = info.activityInfo.packageName;
//應用的主activity類
String cls = info.activityInfo.name;
ComponentName componet = new ComponentName(pkg, cls);
Intent i = new Intent();
i.setComponent(componet);
startActivity(i);
}