yes u can
Use alarm manager or show notifications that the app is running in the background.
Service
// LifecycleService with MutableLiveData If you want to use mvvm
//You can exchange it for the service
public class AlarmService extends LifecycleService {
public static MutableLiveData<String> status =new MutableLiveData<>();
private Notification.Builder builder;
private NotificationChannel notificationChannel;
@Override
public void onCreate() {
super.onCreate();
notificationChannel=new NotificationChannel("channel","channel", NotificationManager.IMPORTANCE_HIGH);
startForeground(500,notification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Log.d("TAG", "run: ");
// your Code
status.postValue("run");//change status If you want to send data to an activity
handler.postDelayed(this, 1000);//change this 1000ms
}
};
handler.postDelayed(runnable, 1000) //change this 1000ms;
return START_STICKY;
}
public Notification notification(){
Intent intent=new Intent(this,getClass());
@SuppressLint("UnspecifiedImmutableFlag")
PendingIntent pendingIntent= PendingIntent.getService(this,1,intent,PendingIntent.FLAG_CANCEL_CURRENT);
builder =new Notification.Builder(this,"channel");
builder.setContentText("The service runs in the forground");
builder.setContentTitle("Service is running");
builder.setSmallIcon(R.drawable.ic_send);
NotificationManager notificationManager= (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
return builder.build();
}
}
Actvity
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName =getPackageName();
PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
Intent intent =new Intent(getApplicationContext(),AlarmService.class);
startService(intent);
AlarmService.status.observe(this, s -> {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
});
Don't forget in manifest
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<service
android:name=".AlarmService"
android:enabled="true"
android:label="Alarm"
android:stopWithTask="false" />