How to Create Forground Service Never Stop when Application is Inactive

百般思念 提交于 2019-12-24 06:35:40

问题


I have created one application in which I want to start service First time open the application.when application is in foreground Every 5 or 10 minutes Local Notification received.but Notification received only When Application Active or Recent app.When Clear the Recent app Notification Does't receive.I wanted this service to keep running on the device.

Sample code of created service and start services: Start the service:

    Intent i=new Intent(MainActivity.this,MyService.class);       
    startService(i);

The service:

    public class MyService extends Service {
    final static String TAG = MyService.class.getName();
    ReceiverCall receiverCall;


    private static final int NOTIFICATION_ID = 1;

    MyService (){
        super();
        }
    class Mythread implements Runnable {
        int service_id;

        Mythread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {
            int i = 0;
            synchronized (this) {
               // while (i < 10) {
                    try {
                        wait(2500);
                        i++;
                        processStartNotification(String.valueOf(i));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
               // }
            }
        }
    }

    @Override
    public void onCreate() {
         receiverCall= new ReceiverCall();
            super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        super.onDestroy();
        Toast.makeText(getApplicationContext(), "Service Task destroyed", Toast.LENGTH_LONG).show();


        Intent myIntent = new Intent(getApplicationContext(), MyService.class);
        startService(myIntent);



    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent myIntent = new Intent(getApplicationContext(), MyService.class);
        startService(myIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

      Thread thread = new Thread(new Mythread(startId));
        thread.start();

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private void processStartNotification(String s) {
        // Do something. For example, fetch fresh data from backend to create a rich notification?

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("Scheduled Notification")
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.colorAccent))
                .setContentText(" Notification Service"+s)
                .setSmallIcon(R.drawable.ic_launcher_background);
        builder.setDeleteIntent(receiverCall.getDeleteIntent(this));
        final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());

    }
    }

BroadcastReceiver Class :

    public class ReceiverCall extends BroadcastReceiver {
    private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
    private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
    private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stops", "Ohhhhhhh");
        context.startService(new Intent(context, MyService.class));
    }
    public static PendingIntent getDeleteIntent(Context context) {
        Intent intent = new Intent(context, ReceiverCall.class);
        intent.setAction(ACTION_DELETE_NOTIFICATION);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    }   

Manifest declaration:

      <service
            android:name=".MyService"
            android:exported="true"
            android:stopWithTask="false"></service>

         <receiver android:name=".ReceiverCall">
            <intent-filter>
                <action android:name="com.servicesex" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

Is it possible to run this service always as when the application pauses and anything else. After some time my application goes pause and the services also go pause or stop. So how can I run this service in background and always.


回答1:


You can use Alarm Manager to schedule a future task in specific time and set it again when it triggered. Sample usage or the new api WorkManager which could help to run task even app got killed.

But i think it is bad practice to keep a service running when your app is removed from system task as the service keep consuming memory & power. Better follow this Guideline




回答2:


public class MyService extends Service {
static final int NOTIFICATION_ID = 100;

public static boolean isServiceRunning = false;

@Override
public void onCreate() {
    super.onCreate();
    startServiceWithNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
        startServiceWithNotification();
    }
    else stopMyService();
    return START_STICKY;
}

// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
    isServiceRunning = false;
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Used only in case of bound services.
    return null;
}


void startServiceWithNotification() {
    if (isServiceRunning) return;
    isServiceRunning = true;

    Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
    notificationIntent.setAction(C.ACTION_MAIN);  // A string containing the action name
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setTicker(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.my_string))
            .setSmallIcon(R.drawable.my_icon)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(contentPendingIntent)
            .setOngoing(true)
//                .setDeleteIntent(contentPendingIntent)  // if needed
            .build();
    notification.flags = notification.flags | Notification.FLAG_NO_CLEAR;     // NO_CLEAR makes the notification stay when the user performs a "delete all" command
    startForeground(NOTIFICATION_ID, notification);
}

void stopMyService() {
    stopForeground(true);
    stopSelf();
    isServiceRunning = false;
}
}

C = are the Strings that must start with the package name



来源:https://stackoverflow.com/questions/50757617/how-to-create-forground-service-never-stop-when-application-is-inactive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!