即使电话处于闲置状态,如何运行服务?

时间:2018-11-14 04:54:17

标签: android database service

我知道这个问题已经被问过多次了。从其他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);

    }
}

我面临的问题是,如果屏幕关闭且设备进入空闲状态,则服务将被终止或不向DB返回任何值。

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

1 个答案:

答案 0 :(得分:1)

我认为,您不应为此目的使用服务。您应该使用某种任务处理程序。其中有很多-AlertManager,JobSheduler等。有时候选择一个确实很棘手。我建议从本文开始:https://medium.com/mindorks/android-scheduling-background-services-a-developers-nightmare-c573807c2705