从外部应用程序启动活动,缺少额外内容

时间:2015-03-29 11:42:05

标签: android android-intent android-activity

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

Intent intent= new Intent(context, SmsAlarm.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(SWITCH_FRAGMENT_REQUEST, true);

context.startActivity(intent);

正如我之前所说的那样,我的活动开始很好,但我放弃了我需要的额外内容。谁能告诉我什么,以及为什么会这样。

2 个答案:

答案 0 :(得分:2)

从窗口小部件打开活动意图的正确方法是使用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 应该是一个const。

答案 1 :(得分:0)

检查此链接。 http://stackoverflow.com/questions/10299461/getting-extra-string-value-from-a-previous-activity-inside-an-onclick-method

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

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

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

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

到Developer.android

Intent Developer.android