2010-01-02 84 views
2

我有三个类主要活动(名为MainMap),一个非活动类(名为MyItemizedOverlay)和一个活动类(名为AudioStream)。 我想从非活动类开始AudioStream活动,但我不知道如何去做。 我想 这是第三类(称为MyItemizedOverlay):使用非活动类的意图

  Intent myIntentA = new Intent(MainMap.this, AudioStream.class); 
      myIntentA.putExtra(AUDIO_STREAM,AUDIO_STREAM_URL); 
      MojProg.this.startActivity(myIntentA); 

,但它不工作,说:类型MainMap没有外围实例在范围上

我应该怎么做访问?我写什么而不是MainMap.this?

回答

2

这不是一个Android问题,因为它是一个Java问题。除非将“MyItemizedOverlay”设置为“MainMap”的内部类(请参阅http://forums.sun.com/thread.jspa?threadID=690545),否则您真正需要的是MyItemizedOverlay将内部引用存储到要用于inent的MainMap对象。

问候, 马克

+0

感谢马克 存储一个内部引用到它想要用于inent的MainMap对象?你能举个例子说明如何做到这一点吗? – Nikola 2010-01-02 18:38:57

+0

通常,您将通过将MainMap引用作为参数传递给MyItemizedOverlay构造函数,然后将其存储在MyItemizedOverlay对象内的数据成员中。但是,如果使用这种方法,则需要处理MainMap被“拆除”并通过onSaveInstanceState和onRestoreInstanceState方法重建,以便维护有效的当前引用。 – Mark 2010-01-02 19:20:20

0
Intent myIntentA = new Intent(MainMap.this, AudioStream.class); 
myIntentA.putExtra(AUDIO_STREAM,AUDIO_STREAM_URL); 
MojProg.this.startActivity(myIntentA); 

这是行不通的。因为“这个”意味着“这个班级”。你不能在另一个类上使用它(是的,你可以,但有不同的方法,请在论坛,本站或oracle网站上研究“this”)。这是警告的原因。

那么它看起来像你的问题是“我如何将上下文拉到非活动类?”。 (Intent()的第一个参数是Context)。

要做到这一点,你可以在你的主要活动创建一个Context即时和您的基本上下文分配给它喜欢:

static Context context; 

.... 

context = this.getBaseContext(); 

不要忘了,是你的主要活动。然后在您的非活性类,你可以拉这种情况下,用同样的意图使用它:

Context context; 
Intent intent; 

....Constructor: 

context = MainActivity.context; 
intent = new Intent(context, YourSecondActivity.class); // you have to declare your second activity in the AndroidManifest.xml 
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this is required to call "Intent()" in a non-activity class. 

//And then you can call the method anywhere you like (in this class of course) 

context.startActivity(intent); 

确定。你已经准备好再走一步。在AndroidManifest.xml中,声明你的第二个活动,就像第一个活动一样;

<activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:screenOrientation="landscape" 
     android:configChanges="keyboard|keyboardHidden|orientation|screenSize"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity 
     android:name=".YourSecondActivity" 
     android:label="@string/app_name" 
     android:screenOrientation="landscape" 
     android:configChanges="keyboard|keyboardHidden|orientation|screenSize"> 
    </activity> 

你现在已经准备好了。但是最后一个警告,不要忘记在打开另一个之前处置你的活动以避免滞后。 玩得开心。