1

我在AppWidgetProvider课堂上有以下代码:

@Override
    public void onUpdate(
....
  Intent mainIntent = new Intent(ctxt, MainActivity.class);
        mainIntent.putExtra("testExtra",true);
        PendingIntent pendingIntent = PendingIntent.getActivity(ctxt, 0, mainIntent, 0);
        widget.setOnClickPendingIntent(R.id.buttonAddwidget, pendingIntent);

...

此代码将仅启动主 Activity,但我想test()从主 Activity 调用函数。
我该怎么做?
我正在尝试使用getExtra,但它不起作用。

4

1 回答 1

1

Why not add some data to the event using putExtra- perhaps a boolean flag or something.

Then in onCreate() you can check for the presence of the data in the intent (which you can access using getIntent()), and call a function if it's there.

EDIT

Using the updated code (with the extra) that you've provided above, you then need to something like the following in your onResume function within MainActivity.class.

if (getIntent().getBooleanExtra("textExtra"))
    doSomeFunction();

getIntent() should give you the calling intent. If this doesn't work it's probably to do with your activity's launchMode setting, and you may have to override the onNewIntent() method to get the intent.

EDIT 2

Try adding the following code to your activity. What it does is handles the times when the activity is not created by the intent, so getIntent() would return the intent used to first create the activity and not the new one (containing the extras). It sets the intent to the new one, so that in onResume() you're able to access that extra.

 @Override
 protected void onNewIntent(Intent intent) {
     //called when the activity is relaunched by a new intent
     setIntent(intent);
     super.onNewIntent(intent);
 }
于 2013-09-17T14:54:15.010 回答