Android:从应用程序类启动新活动。

7

我有一个播放音频的 Android 应用程序,它是从应用程序类播放的。我在应用程序类中有一个 PhoneStateListener,在电话呼叫时暂停音频。

当通话结束时,我想启动特定的活动,但我无法做到。以下是我的代码:

public void getPhoneState(){

TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {

        if (state == TelephonyManager.CALL_STATE_RINGING) {
            if(audio.isPlaying())
               audioPlayer.pause();

        } 
            else if(state == TelephonyManager.CALL_STATE_IDLE) {

                audio.start();
                Intent missintent= new Intent(context,AudioActivity.class);
                missintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(missintent);


        } 
            else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {

            if(audio.isPlaying())
            audioPlayer.pause();

        }
        super.onCallStateChanged(state, incomingNumber);


    }
};

if(mgr != null) {
    mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}

public boolean handleAudio(String source, int id) {

phoneState();
//Code for Playing Audio
.....
.....
}

如果有人能向我展示如何正确地启动活动,我将不胜感激。

谢谢!


我的活动已添加到清单中。从应用程序类启动活动不可能吗? - RagHaven
@RaghavShankar,我正在遇到非常相似的问题,你找到了任何解决方法吗? - MikeIsrael
但我无法做到这一点。 你需要告诉我们发生了什么事情。描述+日志。 - Philippe Girolami
@MikeIsrael 我决定使用Android服务播放音频会更好,这样就变得不太复杂了。 - RagHaven
@RaghavShankar 好的,我知道你已经转向服务了,但如果你改变主意,我已经能够让一些东西工作了,请看我的答案。 - MikeIsrael
显示剩余2条评论
1个回答

21

好的,我知道您已经找到了其他的解决方案,但是我正在尝试破解它,并找到了适合我的东西。我没有调用Intent,而是使用了pendingIntent、Intent过滤器和pending post。以下是给其他人出现此问题的代码片段。

Context context = MyApplication.this.getApplicationContext();
Intent errorActivity = new Intent("com.error.activity");//this has to match your intent filter
errorActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 22, errorActivity, 0);
try {
    pendingIntent.send();
    } 
catch (CanceledException e) {
        // TODO Auto-generated catch block
    e.printStackTrace();
    }

然后在您的清单文件中,只需确保为捕获活动设置意图过滤器即可。

<activity
    android:name="UncaughtErrorDialogActivity"
    android:theme="@android:style/Theme.Dialog" >
    <intent-filter>
        <action android:name="com.error.activity" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接