简体   繁体   中英

How to create a background app (Service) to get the mobile data every 30 sec. The service must working in 24/7

Currently I manage to do get every 30 sec received/transmitted across mobile networks since device boot.

Timer :-

Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(mTimeTask, 0, AppConstants.DATA_TRACKING_PERIOD);

private TimerTask mTimeTask = new TimerTask() {
        @Override
        public void run() {
           long currentRx = TrafficStats.getMobileRxBytes();
           long currentTx = TrafficStats.getMobileTxBytes();
        }
    }
};

Service :-

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (isInstanceCreated()) {
        if(!mSocket.connected()){
           connectConnection();
        }
        return START_STICKY;
    }
    super.onStartCommand(intent, flags, startId);
    connectConnection();
    //Timer starts from here
    mTrafficHelper.startTracking();    
    return START_STICKY;
}

AndroidManifest.xml :-

<!-- Access network/ Internet connection permission -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<service android:name=".services.MyService"
         android:enabled="true"
         android:exported="true"
         android:priority="100" />

Is this the correct way to implement the above requirement? Please suggest.

There is nothing that will keep a Service running 24/7. The Android framework may kill a Service for resources at any time.

In addition, on more modern versions of Android you'll run into Doze mode. Doze is a deep sleep mode to save battery power. It will prevent your service from running every 30 seconds to preserve battery power.

There may be a way around it AlarmManager and using setExactAndAllowWhileIdle. But this is NOT suggested for any Play Store app, you will kill your user's battery.

Really I'd question why you need to get the data so frequently. Odds are you don't and are either over engineering or doing the wrong thing entirely.

There is a another solution I found here and its not 100% answered my question.

Android-Job

Gradle: app

compile 'com.evernote:android-job:1.1.3'

Code:

new JobRequest.Builder(SocketSyncJob.TAG)
                .setPeriodic(JobRequest.MIN_INTERVAL, JobRequest.MIN_FLEX)
                .setRequiresCharging(false)
                .setRequiresDeviceIdle(true)
                .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
                .setRequirementsEnforced(false)
                .setPersisted(true)
                .build()
                .schedule();

Your activity code

AlarmManager am =(AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(getContext(), ScanReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(getContext(), 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60, pi);    

// receiver

public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         //start your service
    }

}

and manifest add this

<receiver android:name=".Receiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
</receiver>

It will call your receiver in one minute 24/7 which is default time, either your app is open or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM