我有一个运行并侦听麦克风输入的Android服务。我希望它在满足特定条件时启动一项活动。为了创建一个Intent,我需要应用程序上下文。我怎么才能得到它?如何从Android服务获取应用程序上下文?
Intent i = new Intent(ctx, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
上述行不启动我的活动。
这里是我的构造
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);
}
}
有myByteReceiver被监听通过音频输入信号。当它找到匹配的信号时,我希望它发起一个活动。
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);
}
}
}
这里是堆栈跟踪
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线是theApplication.startActivity(i);
你可以发布你叫'getApplicationContext'的方法是什么? – Craigy
我发布了它 –
如果您发布了NullPointerException的日志,那将会更有帮助。 – keno