i'm creating and app which notify the user in some specific period of time, i used JobService to let it working automatically and with the app closed, my problem is... there are some devices that my Job simply does not start, i dont know what is happing, because in my cellphone it works nice, but in some of my friends' devices, it doesn't.
I'm sending my JobService's class
package com.medicina.mednews;
public class JobServiceNotification extends JobService {
private static final String TAG = "JobServiceNotification ";
private boolean jobCancelled = false;
String android_id;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference reference, refJob;
@Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
reference= db.getReference().child("Usuarios").child(android_id).child("NoticiasDoPython");
refJob = db.getReference().child("Usuarios").child(android_id).child("JobServiceFinished");
reference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
PrincipalModel principalModell3=snapshot.getValue(PrincipalModel.class);
Log.i("G3",""+principalModell3);
Log.i("GT",snapshot.getKey());
String aa = principalModell3.getData();
String[] aaS = aa.split(" ");
String idNotification = aaS[4];
idNotification = idNotification.replace(":","");
Log.i("IdNotification",idNotification);
addNotification(principalModell3.getTitulo(),principalModell3.getDescrição(),idNotification);
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
for (int i = 0; i < 10; i++) {
copyFirebaseData();
Log.i("Execução","Executei = "+i);
if (jobCancelled) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Job finished");
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
Date currentTime = Calendar.getInstance().getTime();
refJob.child(dateFormat.format(date)).setValue(""+currentTime);
jobFinished(params, false);
}
}).start();
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}
public void copyFirebaseData() {
android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
DatabaseReference questionNodes = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(android_id).child("NoticiasDoPython");
final DatabaseReference toUsersQuestions = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(android_id).child("NoticiasMovidasPeloAndroid");
questionNodes.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String KeyChild = questionCode.getKey();
Log.i("KEYYY",KeyChild);
String DateAntiga = questionCode.child("Data").getValue(String.class);
String DescricaoAntiga = questionCode.child("Descrição").getValue(String.class);
String TituloAntiga = questionCode.child("Titulo").getValue(String.class);
String LinkAntiga = questionCode.child("Link").getValue(String.class);
String ImagemAntiga = questionCode.child("Imagem").getValue(String.class);
String Id = questionCode.child("IdNoticia").getValue(String.class);
toUsersQuestions.child(KeyChild).child("Id").setValue(Id);
toUsersQuestions.child(KeyChild).child("Imagem").setValue(ImagemAntiga);
toUsersQuestions.child(KeyChild).child("Data").setValue(DateAntiga);
toUsersQuestions.child(KeyChild).child("Descrição").setValue(DescricaoAntiga);
toUsersQuestions.child(KeyChild).child("Link").setValue(LinkAntiga);
toUsersQuestions.child(KeyChild).child("Titulo").setValue(TituloAntiga);
questionNodes.child(KeyChild).removeValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void addNotification(String titleNot,String DescriptNot, String idNotification) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default", "Channel name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Channel description");
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
.setSmallIcon(R.drawable.ic_baseline_nuvem_deletar)
.setContentTitle(getResources().getString(R.string.app_name))
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(titleNot)
.setPriority(Notification.PRIORITY_HIGH)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(DescriptNot))
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentText(DescriptNot);
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//ESTAMOS DEFININDO UM ID ALEATÓRIO PARA GERAR MÚLTIPLAS NOTIFICAÇÕES
Calendar cal = Calendar.getInstance();
long millisecondOfDay =
TimeUnit.HOURS.toMillis(cal.get(Calendar.HOUR_OF_DAY)) +
TimeUnit.MINUTES.toMillis(cal.get(Calendar.MINUTE)) +
TimeUnit.SECONDS.toMillis(cal.get(Calendar.SECOND)) +
cal.get(Calendar.MILLISECOND);
manager.notify(Integer.parseInt(idNotification), builder.build()); //IREMOS DEFINIR UM ID COM UUID, MAS DEPOIS TEREMOS QUE MUDAR POIS ISSO NÃO ESTÁ CERTO !!! POSSIVELMENTE TEREMOS QUE IR PRO JSON
//ESTAMOS DEFININDO UM ID ALEATÓRIO PARA GERAR MÚLTIPLAS NOTIFICAÇÕES
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.QUICKBOOT_POWERON" />
<application
android:name=".FirebaseHandler"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="@style/Theme.Mednews"
tools:targetApi="31">
<receiver
android:name=".StartReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name=".JobServiceNotification"
android:permission="android.permission.BIND_JOB_SERVICE" />
<activity
android:name=".MedMenu.activity.MainActivity"
android:exported="true"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
</application>
</manifest>
I tried to use the normal JobService class, but it simply doesn't work in some specific devices, the result is that my notifications don't start