I am trying to make a background service that runs even if the application is closed. this services is supposed to listen to Firebase changes, and start the application according to a trigger. I don't know whether I am missing something in the code or not even close to the right answer, but here is my code :
public class FireBaseService extends Service {
private HashMap<String, String> fireBaseBattery;
@Override
public void onCreate() {
super.onCreate();
fireBaseBattery = new HashMap<>();
final Firebase firebaseRef_Battery = new Firebase("the url i want to take data from");
firebaseRef_Battery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
fireBaseBattery = (HashMap<String, String>) dataSnapshot.getValue();
String battery = (String) fireBaseBattery.get("battery");
int battery_int = Integer.parseInt(battery);
System.out.println("SERVICE FIREBASE : " + battery);
if (battery_int <= 10) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
And this is the manifest :
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:name=".ParseApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service android:enabled="true"
android:name=".FireBaseService">
</service>
<activity
android:name=".Launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Edit : I added a line in MainActivity.class to start the service
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, FireBaseService.class));
}