从外部应用程序开始 activity,缺少附加功能

Starting activity from outside application, missing extras

我的应用程序中有一个小部件,使用 startActivity() 应该可以从该小部件到应用程序,我还需要通过 Intent 开始 [=23] 传递一些额外内容=].但是在 onCreate()Bundle 是空的!?! 试图解决这个问题,有人通过覆盖 onNewIntent() 解决了这个问题,因为如果我的 activity 的一个实例已经存在,就可以调用它,但也没有成功,因为 onNewIntent() 永远不会得到叫。那么这里发生了什么?我只想从我的应用程序外部启动一个 activity 并使用 Intent?

传递一些额外内容
Intent intent= new Intent(context, SmsAlarm.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(SWITCH_FRAGMENT_REQUEST, true);

context.startActivity(intent);

正如我之前所说,我的 activity 以这种方式开始时很好,但我失去了我需要的额外功能。谁能告诉我这是怎么回事,为什么会这样。

从小部件打开 Activity 意图的正确方法是使用 PendingIntent。这样做应该不会有任何问题。

按照 docs:

中所述设置 PendingIntent
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, ExampleActivity.class);
// Add Extra
intent.putExtra("MY_EXTRA", "extra");

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);

现在,像往常一样获得额外的:

Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
    mMyExtra = extras.getString("MY_EXTRA", null);
}

MY_EXTRA 应该是某处的常量。

检查此 link。

对于另一个 Activity,在 onCreate 方法中获取字符串必须使用

saveMe = getIntent().getExtras().getString("string");

如果你有布尔值,你可以使用

boolean defaultValue = false;
boolean yourValue = getIntent().getBooleanExtra(YOUR_EXTRA, defaultValue);

至Developer.android

Intent Developer.android