问题描述
我以前有一个通过一项活动启动的前台服务。启动服务的代码包含在上述活动中。
现在,我想使用非活动类启动此服务,该类可以从不同的活动中调用。在执行此操作时出现错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ComponentName android.content.Context.startService(android.content.Intent)' on a null object reference
该工作代码块以前包含在单个活动中(我们将其称为“ ActivityClass”),如下所示:
private void serviceWrapper(String command){
Intent service = new Intent(ActivityClass.this,Recorder.class);
switch (command){
case "start":
service.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
service.putExtra("recordAudio",RECORD_AUdio);
startService(service);
break;
etc...
}
}
我试图将其移至非活动类的尝试如下:
public class ServiceWrapper extends AppCompatActivity {
// variable to hold context passed
private Context context;
public ServiceWrapper(Context context){
this.context=context;
}
public void serviceControl(String command){
Intent service = new Intent(context,Recorder.class);
switch (command)
{
case "start":
service.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
service.putExtra("recordAudio",RECORD_AUdio);
startService(service);
break;
etc....
}
我想通过多个活动来调用它:
private void startWrapper() {
//Instantiate the class
ServiceWrapper serviceWrapper = new ServiceWrapper(ActivityClass.this);
//Check for permissions needed
if (hasPermissionsGranted(Constants.PERMISSION_SETTINGS.VIDEO_PERMISSIONS)){
serviceWrapper.serviceControl("start");
}
else {
//kick off async request for permission
ActivityCompat.requestPermissions(this,Constants.PERMISSION_SETTINGS.VIDEO_PERMISSIONS,REQUEST_VIDEO_PERMISSIONS);
}
}
但是不幸的是我遇到了这个错误。我不是一个知识渊博的程序员,如果这很明显,请原谅我。
解决方法
通常,这不是在android上启动前台服务的方法。
应该是这样的:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context,HelloService.class));
} else {
context.startService(new Intent(context,HelloService.class));
}
如果您不在活动中,则需要一种方法来检索应用程序上下文。通常,这可以通过构造函数将上下文存储为变量来完成,以便稍后使用。例如,创建一个将应用程序上下文存储为变量的新类实例,使用该上下文在应用程序中的其他位置启动服务。
或者根据您的课程扩展或实现的方式
getActivity().getApplicationContext();
如果您使用的是意图服务,则应首先启动该服务,以便对其进行初始化,然后再传递意图。