2013-03-25 103 views
2

我已经阅读过某处(但我无法再找到它),应该可以在设备主屏幕上从快捷方式发送附加内容。我成功创建了一个快捷方式,但Bundle extras = getIntent().getExtras();给出了一个空指针。快捷方式主屏幕,如何发送演示文稿

我创建快捷方式如下:

Intent shortcutIntent = new Intent(this.getApplicationContext(), 
         Shortcut_Activity.class); 

       shortcutIntent.setAction(Intent.ACTION_MAIN); 

       Intent addIntent = new Intent(); 
       addIntent 
         .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
       addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); 
       addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, 
         Intent.ShortcutIconResource.fromContext(this.getApplicationContext(), 
           R.drawable.ic_shortcut)); 
       addIntent.putExtra("ID", id); //THIS IS THE EXTRA DATA I WANT TO ATTACH 
       addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); 
       this.getApplicationContext().sendBroadcast(addIntent); 

这可能吗?如果呢,如何?

回答

2

由于这里找到:http://www.joulespersecond.com/2010/04/android-tip-effective-intents/

幸运的是,有一个解决方案。更好的方法是将行ID作为URI的一部分,而不是作为额外的一部分。所以上面的代码变得像这样:

void returnShortcut(int rowId, String shortcutName) { 
    Intent i = new Intent(this, ShowInfoActivity.class); 
    i.setData(ContentUris.withAppendedId(BASE_URI, rowId)); 
    Intent shortcut = new Intent(); 
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, i); 
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName); 
    setResult(RESULT_OK, shortcut); 
    finish(); 
} 

BASE_URI可以是任何东西,但它应该是东西是特定于应用程序。重点在于,数据URI用于确定两个意图是否相等,因此系统最终会为此创建一个新的活动,即使具有不同数据的活动位于您的任务堆栈上。

4

是的,我已经实现了它,下面是代码

private void addShortcut() { 
    //Adding shortcut for MainActivity 
    //on Home screen 
    Intent shortcutIntent = new Intent(getApplicationContext(), 
      HOMESHORTCUT.class); 
    //Set Extra 
    shortcutIntent.putExtra("extra", "shortCutTest "); 

    shortcutIntent.setAction(Intent.ACTION_MAIN); 

    Intent addIntent = new Intent(); 
    addIntent 
      .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut"); 
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, 
      Intent.ShortcutIconResource.fromContext(getApplicationContext(), 
        R.drawable.ic_launcher)); 

    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); 

    getApplicationContext().sendBroadcast(addIntent); 


} 
//GET Extra in HOMESHORTCUT activity. 
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mTextExtra=new TextView(this); 
     Bundle bundel=getIntent().getExtras(); 
     String getExString=getIntent().getExtras().getString("extra"); 
     mTextExtra.setText(getExString); 
     setContentView(mTextExtra); 
    } 
+0

但是这个代码将崩溃,如果捆绑,这里命名临时演员(无论何种原因)是空还是 – JacksOnF1re 2014-12-05 16:09:56

+0

以防万一你还有空例外,**删除旧的快捷方式**,让新的创建如果你使用'addIntent.putExtra(“duplicate”,false);' – Choletski 2017-08-31 13:30:00

相关问题