android - 如何创建应用程序不活动时永不停止的前台服务

标签 android google-maps android-fragmentactivity

我创建了一个要在其中启动服务的应用程序 第一次打开该应用程序。当应用程序位于前台时 每 5 或 10 分钟收到本地通知。但仅当应用程序处于 Activity 状态或最近使用的应用程序时收到通知。当清除最近的应用程序时应用程序通知未收到。我希望此服务在设备上继续运行。

创建服务和启动服务的示例代码: 启动服务:

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

服务:

    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);
    }
    }   

list 声明:

      <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>

是否可以在应用程序暂停或其他任何情况下始终运行此服务。一段时间后,我的应用程序暂停,服务也暂停或停止。那么我如何才能始终在后台运行此服务。

最佳答案

您可以使用警报管理器将 future 的任务安排在特定时间,并在触发时再次设置。 Sample usage或新的API WorkManager即使应用程序被杀死,这也可以帮助运行任务。

但我认为当您的应用程序从系统任务中删除时保持服务运行是不好的做法,因为该服务不断消耗内存和电量。最好遵循这个Guideline

关于android - 如何创建应用程序不活动时永不停止的前台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50757617/

相关文章:

Android ExpandableListView 不会在返回 LinearLayout 或 View 时展开

javascript - 如何将数据映射到 map (Google map )上的邮政编码?

java - 将 HashMap 添加到标记以显示图像不会返回该特定标记的正确图像

ios - 在 Google map objective-c 中调整、拖动和缩放 GMSCircle

java - 在 fragment 后面添加方法

android - 如何获取另一个尚未开始的 Activity 的上下文?

android - 如何将其添加到 fragment 中

javascript - 在 Phonegap Android 中存储值的最简单方法

android - 最新的 Android 模拟器 : HTTPS Network Issues - Chrome

android - ScrollView 中的 RecyclerView 不起作用