[英]creating android app shortcut on the home screen
我需要在主屏幕上為我的應用程序添加一個快捷方式(以編程方式)。 我知道默認情況下應用程序商店會執行此操作,但首先,該應用程序不會出現在谷歌應用程序商店中。 我搜索了很多,一遍又一遍地發現基本相同的代碼行,它似乎對我不起作用。
我使用的代碼:在清單中:
<activity android:name=".MainScreenActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
在 onCreate 方法中,我調用了執行以下操作的函數:
private boolean createShortcut()
{
//create shortcut intent
Intent shortcutIntent = new Intent(getApplicationContext(),MainScreenActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
//create intent to add and define the shortcut
Intent addingIntent = new Intent();
addingIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,shortcutIntent);
addingIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"SenseGuard");
addingIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(getApplicationContext(),R.drawable.peak_detection_icon));
addingIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addingIntent);
}
我嘗試將“getApplicationContext()”切換為“this”。 我嘗試使用實際的平板電腦和模擬器,但無法正常工作。
這樣做:
第1步:
更新您的 manifest.xml :
<uses-permission
android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
第2步:
在您的 MainActivity.java 創建addShortcut()方法並在它的塊中放置以下代碼:
private void addShourcut(){
Intent shortCutIntent = new Intent(getApplicationContext() ,MainActivity.class);
shortCutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT , shortCutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME , "Convertor");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE ,
Intent.ShortcutIconResource.fromContext(getApplicationContext() , R.mipmap.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
addIntent.putExtra("duplicate" , false);
getApplicationContext().sendBroadcast(addIntent);
}
第三步:
為要創建快捷方式的視圖設置 onClickListener :
img_pin = (ImageView) findViewById(R.id.img_pin);
img_pin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addShourcut();
Toast.makeText(MainActivity.this, "shortcut created !", Toast.LENGTH_SHORT).show();
}
});
這對我有用......快樂的編碼......:)
該代碼不能保證工作。 該廣播也由ShortcutManagerCompat發送(您可能應該使用它而不是手動發送廣播)。
然而,這有兩個問題。
不保證您的默認啟動器會收聽此廣播。 例如,Nova Launcher 默認禁用此行為。 其他發射器甚至可能根本不聽那個動作。
在 Android Oreo (26) 及更高版本上,這不會像您期望的那樣工作(閱讀我鏈接的方法的評論以獲取更多詳細信息)。
您仍然可以使用此邏輯並希望它適用於您的某些用戶,但請記住,許多默認啟動器甚至不再具有應用程序抽屜,因此添加快捷方式可能會給您的用戶提供重復的圖標。 另外,我知道,至少對我來說,我的主屏幕按我想要的方式組織起來,如果我安裝了一個應用程序,它會把自己添加到我的主屏幕上真的很煩人。
如果您使用的是默認AOSP發射器(或接近叉),然而,它不工作,請確保您添加到您的清單:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.