我想通过闹钟管理器启动我的服务。我写下面的代码。当我的应用程序处于后台或前台时,但当我杀死我的应用程序时(我的意思是从最近的应用程序中滑动应用程序),此代码运行良好,程序会出错。我不知道我的问题是什么,如何解决这个问题。
错误:
Caused by: java.lang.NullPointerException at com.company.test.helper.ServiceSchedular.startService(ServiceSchedular.java:74)
我有一个类,从下面的应用程序扩展:
public class KITILApplication extends Application{
private static Context context;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
ACRA.init(this);
ORMDroidApplication.initialize(this);
KITILApplication.context=getApplicationContext();
}
public static Context getappContext(){
return KITILApplication.context;
}
}
我的ServiceSchedularService用于安排启动服务的警报,如下所示:
public class ServiceSchedular {
//Called from my main activity
private ServiceSchedular() {
alarmManager = (AlarmManager) KITILApplication.getappContext().getSystemService(Context.ALARM_SERVICE);
}
private static void startService(Date startDate) {
uniqueIdForStart = (int) Calendar.getInstance().getTimeInMillis();
//PlEASE NOTICE: I checked my application via both of startintent(comment startIntent and startIntent)
Intent startIntent = new Intent(KITILApplication.getappContext(), LocationService.class);
//Intent startIntent = new Intent("com.company.test.START_SERVICE");
PendingIntent startPendingIntent = PendingIntent.getService(KITILApplication.getappContext(), uniqueIdForStart, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//I get error from below line !! Line = 74
alarmManager.set(AlarmManager.RTC_WAKEUP, millisToStartDate, startPendingIntent);
stopService(startDate);
}
public static void checkNextPeriod() {
.
.
startService(new Date(millisDate));
}
}
我有一个调用checkNextPeriod的broadcastReciever,在checkNextPeriod中,我调用了startService方法。
的AndroidManifest.xml:
<service android:name=".Service.LocationService">
<intent-filter>
<action android:name="com.company.test.START_SERVICE"></action>
</intent-filter>
</service>
我不知道我的问题是针对alarmManager对象或意图对象或应用程序上下文还是其他事情。请帮我。
答案 0 :(得分:0)
你的问题在这里:
private ServiceSchedular() {
alarmManager = (AlarmManager) KITILApplication.getappContext().getSystemService(Context.ALARM_SERVICE);
}
不要在构造函数中执行此操作。只需在需要时拨打getSystemService()
即可。