|
package varunon9.me.dynamicwallpaper; |
|
|
|
import android.app.Notification; |
|
import android.app.NotificationChannel; |
|
import android.app.NotificationManager; |
|
import android.app.PendingIntent; |
|
import android.app.Service; |
|
import android.content.Intent; |
|
import android.os.Build; |
|
import android.os.IBinder; |
|
import android.util.Log; |
|
|
|
import androidx.core.app.NotificationCompat; |
|
|
|
public class MyService extends Service { |
|
private String TAG = "MyService"; |
|
public static boolean isServiceRunning; |
|
private String CHANNEL_ID = "NOTIFICATION_CHANNEL"; |
|
|
|
public MyService() { |
|
Log.d(TAG, "constructor called"); |
|
isServiceRunning = false; |
|
} |
|
|
|
@Override |
|
public void onCreate() { |
|
super.onCreate(); |
|
Log.d(TAG, "onCreate called"); |
|
createNotificationChannel(); |
|
isServiceRunning = true; |
|
} |
|
|
|
@Override |
|
public IBinder onBind(Intent intent) { |
|
return null; |
|
} |
|
|
|
@Override |
|
public int onStartCommand(Intent intent, int flags, int startId) { |
|
Log.d(TAG, "onStartCommand called"); |
|
Intent notificationIntent = new Intent(this, MainActivity.class); |
|
PendingIntent pendingIntent = PendingIntent.getActivity(this, |
|
0, notificationIntent, 0); |
|
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) |
|
.setContentTitle("Service is Running") |
|
.setContentText("Listening for Screen Off/On events") |
|
.setSmallIcon(R.drawable.ic_wallpaper_black_24dp) |
|
.setContentIntent(pendingIntent) |
|
.setColor(getResources().getColor(R.color.colorPrimary)) |
|
.build(); |
|
|
|
startForeground(1, notification); |
|
return START_STICKY; |
|
} |
|
|
|
private void createNotificationChannel() { |
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { |
|
String appName = getString(R.string.app_name); |
|
NotificationChannel serviceChannel = new NotificationChannel( |
|
CHANNEL_ID, |
|
appName, |
|
NotificationManager.IMPORTANCE_DEFAULT |
|
); |
|
NotificationManager manager = getSystemService(NotificationManager.class); |
|
manager.createNotificationChannel(serviceChannel); |
|
} |
|
} |
|
|
|
@Override |
|
public void onDestroy() { |
|
Log.d(TAG, "onDestroy called"); |
|
isServiceRunning = false; |
|
stopForeground(true); |
|
|
|
// call MyReceiver which will restart this service via a worker |
|
Intent broadcastIntent = new Intent(this, MyReceiver.class); |
|
sendBroadcast(broadcastIntent); |
|
|
|
super.onDestroy(); |
|
} |
|
} |
16 minutes is too long. I'm monitoring the call log and I don't want to miss calls in the middle. Also foreground service will take space in the notification area which is annoying. This code used to work 12 years ago and on blackberry devices. This google system is so badly designed.