使用来自非活动类的Intent

时间:2010-01-02 18:11:12

标签: android class android-activity package android-intent

我有三个类,一个主要活动(名为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 个答案:

答案 0 :(得分:2)

这不是Android问题,而是Java问题。除非你将“MyItemizedOverlay”作为“MainMap”的内部类(参见http://forums.sun.com/thread.jspa?threadID=690545),否则你真正需要的是MyItemizedOverlay存储对它想要用于inent的MainMap对象的内部引用。 / p>

此致 标记

答案 1 :(得分:0)

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

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

看起来您的问题是“如何将上下文拉到非活动类?”。 (Intent()的第一个参数是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>

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

相关问题