Java 如何从Android服务获取应用程序上下文?

Java 如何从Android服务获取应用程序上下文?,java,android,android-intent,android-service,android-activity,Java,Android,Android Intent,Android Service,Android Activity,我有一个Android服务正在运行并监听麦克风输入。我希望它在满足特定标准时启动一项活动。为了创建意图,我需要应用程序上下文。我怎样才能得到它 Intent i = new Intent(ctx, SONR.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ctx.startActivity(i); 上面的行不会启动我的活动 private class SONRByteReceiver implements ByteReceiver {

我有一个Android服务正在运行并监听麦克风输入。我希望它在满足特定标准时启动一项活动。为了创建意图,我需要应用程序上下文。我怎样才能得到它

Intent i = new Intent(ctx, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
上面的行不会启动我的活动

private class SONRByteReceiver implements ByteReceiver {
    private long lastplaytime = 0;
    private long lastmutetime = 0;
    private long lastskiptime = 0;
    private long lastvolutime = 0;
    private long lastbacktime = 0;

    public void receiveByte(int receivedByte) {
        try {
            theKeyEvent = -1;

            if (ismuted) {
                if (receivedByte != MUTE) {
                    volume = 0;
                    ismuted = false;
                }
            }

            switch (receivedByte) {

            case SONR_HOME:
                Log.d(TAG, "HOME");

                Intent i = new Intent(ctx, SONR.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                theApplication.startActivity(i);

                break;
            default:
                Log.d(TAG, "default");
                Log.d(TAG,"RECEIVED " + receivedByte);
                // LogFile.MakeLog("RECEIVED " + receivedByte);
                break;
            }

            if (theKeyEvent >= 0) {
                sendbroadcast();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorReporter.getInstance().handleException(e);
        }
    }
}
这是我的构造函数

public SONRClient(Context c, AudioRecord ar, int buffsize, final AudioManager am) {
    theAudioManager = am;
    theaudiorecord = ar;
    bufferSize = buffsize;
    ctx = c;
    CLIENT_ON = true;
}
这是我的onCreate

@Override
public void onCreate() {
    try {
        // LogFile.MakeLog("\n\nSONRClient CREATED");
        clientStopReceiver = new StopReceiver();
        ctx.registerReceiver(clientStopReceiver, 
            new IntentFilter(SONR.DISCONNECT_ACTION));
        myByteReceiver = new SONRByteReceiver();
        theListener = new MicSerialListener(
            theaudiorecord, bufferSize, myByteReceiver);
        theApplication = getApplication();
    } catch (Exception e) {
        e.printStackTrace();
        ErrorReporter.getInstance().handleException(e);
    }
}
java.lang.NullPointerException
    at com.sonrlabs.test.sonr.SONRClient$SONRByteReceiver.receiveByte(SONRClient.java:320)
    at com.sonrlabs.test.sonr.AudioProcessor.processSample(AudioProcessor.java:145)
    at com.sonrlabs.test.sonr.AudioProcessor.run(AudioProcessor.java:58)
有MyByTereReceiver通过音频输入监听信号。当它找到匹配的信号时,我希望它启动一个活动

private class SONRByteReceiver implements ByteReceiver {
    private long lastplaytime = 0;
    private long lastmutetime = 0;
    private long lastskiptime = 0;
    private long lastvolutime = 0;
    private long lastbacktime = 0;

    public void receiveByte(int receivedByte) {
        try {
            theKeyEvent = -1;

            if (ismuted) {
                if (receivedByte != MUTE) {
                    volume = 0;
                    ismuted = false;
                }
            }

            switch (receivedByte) {

            case SONR_HOME:
                Log.d(TAG, "HOME");

                Intent i = new Intent(ctx, SONR.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                theApplication.startActivity(i);

                break;
            default:
                Log.d(TAG, "default");
                Log.d(TAG,"RECEIVED " + receivedByte);
                // LogFile.MakeLog("RECEIVED " + receivedByte);
                break;
            }

            if (theKeyEvent >= 0) {
                sendbroadcast();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorReporter.getInstance().handleException(e);
        }
    }
}
这是stacktrace

@Override
public void onCreate() {
    try {
        // LogFile.MakeLog("\n\nSONRClient CREATED");
        clientStopReceiver = new StopReceiver();
        ctx.registerReceiver(clientStopReceiver, 
            new IntentFilter(SONR.DISCONNECT_ACTION));
        myByteReceiver = new SONRByteReceiver();
        theListener = new MicSerialListener(
            theaudiorecord, bufferSize, myByteReceiver);
        theApplication = getApplication();
    } catch (Exception e) {
        e.printStackTrace();
        ErrorReporter.getInstance().handleException(e);
    }
}
java.lang.NullPointerException
    at com.sonrlabs.test.sonr.SONRClient$SONRByteReceiver.receiveByte(SONRClient.java:320)
    at com.sonrlabs.test.sonr.AudioProcessor.processSample(AudioProcessor.java:145)
    at com.sonrlabs.test.sonr.AudioProcessor.run(AudioProcessor.java:58)

第320行是应用程序。startActivity(i)

您可以在服务中使用
getApplicationContext()
来获取应用程序上下文

试用

getApplication().startActivity(i);

您认为启动活动需要应用程序上下文的断言是不准确的。您可以,包括作为上下文的服务。

更改此选项:

Intent i = new Intent(ctx, SONR.class); 
致:


boom.

getBaseContext()返回上下文,因为每个活动都扩展了上下文类

每个服务都有自己的上下文,只需使用该类。您不需要将服务传递给活动的上下文。

服务中不需要活动上下文

Intent i = new Intent(ctx, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
只需像在活动中那样做

服务和活动都是上下文的子类


您不能在其公共空构造函数中调用
getApplicationContext()
,否则它将给您一个
NullPointerException

,只需执行此操作即可访问服务上下文

Intent i = new Intent(Service.this, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);


只有在服务的“onCreate()”之后才有非空上下文:在构造函数中获取服务的上下文不是一个好主意(还不是任何上下文),请使用“onCreate”方法中的简单“getApplicationContext()”获取它。

我在尝试getApplicationContext()时遇到空指针异常我更新了代码。我引用了上下文,但我的活动没有显示。我做错什么了吗?你是怎么开始服务的?您能否使用服务中更完整的代码编辑您的问题,例如您尝试在哪些生命周期方法中启动活动?请尝试移动
theApplication=getApplication()
到onCreate的第一行仍然为应用程序的
获取nullpointerexception.startActivity(i)
能否在中发布调用的方法
getApplicationContext
?如果发布获取的NullPointerException的日志会更有帮助。您的代码似乎都没有为ctx变量赋值。查看您的代码以查看“ctx”在何处被赋值,并围绕赋值进行一些打印,以查看何时以及是否被赋值。ctx在我的构造函数中被赋值。我也可以发布代码,我还可以从上下文打印出包名。它做得很好。问题在于触觉。不知道为什么。我只是用startActivity()尝试了一下,但还是得到了一个nullpointerexception。更新了带有更多代码的问题显示空指针的堆栈轨迹。如果您在该类中使用空服务,这不是因为空服务。问题中的stacktrace是调试时打印的全部内容。关于如何进一步调试有什么想法吗?不可能,您将在其他地方遇到空指针异常。如果您的服务正在运行,则上下文不能为空。请尝试单击以下行:com.sonrlabs.test.sonr.AudioProcessor.processSample(AudioProcessor.java:145)或该行下方n上方的行,以查找何时变为空。ctx是什么??您是否从服务启动上述指令?@Lisitso
ctx
是一个
Context
变量如果您已经将ctx作为上下文,为什么要获取应用程序上下文,然后启动活动?为什么不简单地调用ctx.startActivity()?在
服务
类中,调用
getApplicationContext()
是一个安全的地方?@JJD不调用getApplicationContext(),调用getBaseContext(),正如Vishal Android Developer所写的那样。问题仍然在于调用哪个方法是安全的。