首页 > 解决方案 > 即使手机空闲,如何运行服务?

问题描述

我知道这个问题已经被问过很多次了。从其他 SO 问题来看,这就是我尝试过的。我每 15 分钟将设备位置和电话状态返回到 SQLITE,并在第二天将其发送到服务器。手机空闲时如何避免服务被Android杀死?(转换为系统应用程序是不可能的。)

@Override
    public void onCreate() {
        Log.e("onCreate", "Service Method");

        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if (mTimer != null) {// Cancel if already existed
            mTimer.cancel();
            mTimer = null;
        }
        mTimer = new Timer(); //recreate new
        mTimer.scheduleAtFixedRate(new ConnectActivity(), 0, 900000); //Schedule task
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        startServiceForeground(intent, flags, startId);
        return Service.START_STICKY;
    }

    public int startServiceForeground(Intent intent, int flags, int startId) {

        Intent notificationIntent = new Intent(this, DeviceStatusService.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, "channel_id")
                .setContentTitle("NOTIFICATION NAME")
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.default)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();

        startForeground(300, notification);

        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent intent=new Intent(this,this.getClass());
        startService(intent);
    }

    @Override
    public void onDestroy() {
        Log.e("onDestroy", "Service Method");
        mTimer.cancel(); //For Cancel Timer
        mTimer.purge();
        mTimer = null;
        super.onDestroy();
        Intent broadcastIntent = new Intent("RestartService");
        sendBroadcast(broadcastIntent);
    }

另外,我用过这个manifest.xml

    <receiver
        android:name=".ServiceRestarterBroadcastReceiver"
        android:enabled="true"
        android:label="RestartServiceWhenStopped">
        <intent-filter>
            <action android:name="RestartService" />
        </intent-filter>
    </receiver>

<service
        android:name=".DeviceStatusService"
        android:enabled="true"
        android:stopWithTask="false"/>

ServiceRestarterBroadcastReceiver.class

public class ServiceRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
    /*context.startService(new Intent(context.getApplicationContext(), DeviceStatusService.class));*/
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(new Intent(context, DeviceStatusService.class));
            } else {
                context.startService(new Intent(context.getApplicationContext(), DeviceStatusService.class));
            }
        }
    }, 60000);

    }
}

我面临的问题是,如果屏幕关闭并且设备进入空闲状态,服务要么被杀死,要么不向数据库返回任何值。

PS:在使用设备时它工作正常。特别是当您不使用该设备时,此问题仍然存在。

标签: androiddatabaseservice

解决方案


我认为,您不应该为此目的使用服务。您应该使用某种任务调度程序。它们有很多——AlertManager、JobSheduler 等。有时选择一个真的很棘手。我建议从这篇文章开始:https ://medium.com/mindorks/android-scheduling-background-services-a-developers-nightmare-c573807c2705


推荐阅读