I would like to start a Thread when the Android started, so I made something like this
public class StartUpWelcomer extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
arg0.startService(new Intent(arg0, StartUpService.class));
}
With my Manifest:
<receiver android:name=".StartUpWelcomer">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".StartUpService" />
And this is my StartUpService class
public class StartUpService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
BackgroundApplication application = (BackgroundApplication)this.getApplication();
ReminderThread reminderThread = new ReminderThread(null);
if(!reminderThread.failed)
{
reminderThread.start();
application.setRunningThread(reminderThread);
Log.d("SERVICE", "CREATION CONFIRMED");
}
else
{
Log.d("SERVICE", "CREATION CANCELLED");
}
}
And here’s the code for the ReminderThread class
public ReminderThread(Context ctx)
{
this.ctx = ctx;
db = new SQLdb(ctx);
//And there's some other code here that accessed the database functions.
}
OK, so here’s my intention… I would like the StartUpWelcomer to activate the StartUpService (and it’s working).
StartUpService will instantiate a new Thread, activating it and keeping it accessible in my application (which is called as BackgroundApplication class).
And here’s the problem… The ReminderThread actually need to access database (SQLite here), so the ReminderThread instantiated the database to access it. But, my database constructor need a Context to be instantiated. I have no idea where to get the Context here (from the Service class) where I usually get it from Activity class…. (temporarily I put “null” there)
Another problem is, somehow I found that this always cause a NullPointerException…
If you initialize ReminderThread in Service then use ApplicationContect like
new ReminderThread(getApplicationContext());which is found in Service class.