Stworzyłem Service, uruchamia się przy uruchomieniu aplikacji i potem gdzies tam sobie działa w tle.
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService();
}
public void startService(){
Intent intent = new Intent(this, MyFirebaseMessagingService.class);
startService(intent);
}
}
Service
public class MyFirebaseMessagingService extends Service{
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//różne rzeczy które robi service
return START_STICKY;
}
@Override
public void onDestroy() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
I wszystko pięknie działało.
Potem odkryłem, że po restarcie telefonu service nie działa (no bo nie miał prawa działać ponieważ nie był uruchomiony). Trzeba było uruchomić aplikację żeby uruchomić service.
Napisałem więc, zgodnie z instrukcjami które znalazłem w Internecie klasę która miała uruchamiać service po restarcie telefonu
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Intent pushIntent = new Intent(context, MyFirebaseMessagingService.class);
context.startService(pushIntent);
}
}
}
Dodałem również uprawnienia do manifestu
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.piotr.testwebapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".FirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
Po restarcie service się uruchamia ale...
Po pewnym czasie android "ubija" service (chyba zamyka procesy) i service nie działa. Gdy uruchomię aplikacje albo zrestartuje telefon wszystko wraca do normy czyli service działa.
Wie ktoś co spieprzyłem?