[英]How can I get the application context from an Android Service?
我有一个正在运行并侦听麦克风输入的 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);
每个服务都有自己的上下文,只需使用那个。 您不需要将服务传递给活动的上下文。
不需要服务中的活动上下文。
Intent i = new Intent(ctx, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
就像你在活动中所做的那样
Service 和 Activity 都是 Context 的子类。
改变这个:
Intent i = new Intent(ctx, SONR.class);
到:
Intent i = new Intent(getApplicationContext(),SONR.class);
getBaseContext()返回上下文,因为每个活动都扩展了 Context 类
你不能在它的公共空构造函数中调用getApplicationContext()
,否则它会给你一个NullPointerException
。
只需执行此操作即可访问服务上下文
Intent i = new Intent(Service.this, SONR.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
只有在服务的“onCreate()”之后才有非空上下文:在构造函数中获取服务的上下文不是一个好主意(还没有任何上下文),使用简单的“getApplicationContext()”在构造函数中获取它'onCreate' 方法。
ctx.getApplicationContext().startActivity(i)
繁荣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.