Call multiple services in background in android

2019-08-28 00:50发布

I have to call multiple services in background for a project in android app. In each services i have to call separate web service and get some data and process it with local sqlite database. I am able to call each service separately and can manipulate its result with local database. But not able to call all services in a sequence. my code is as below:

@Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Timer timer = new Timer();

        final SyncTableUsers syncUserObj = new SyncTableUsers(LocalService.this);
        final SyncTableVehicles syncVehicleObj = new SyncTableVehicles(this);
        final SyncTableLicenses syncLicenseObj = new SyncTableLicenses(this);
        final SyncTableTags syncTagObj = new SyncTableTags(this);
        final SyncTableTagMappings syncTagMapObj = new SyncTableTagMappings(this);
        final SyncTableAddresses syncAddressObj = new SyncTableAddresses(this);
        final SyncTableDispatches syncDispatchObj = new SyncTableDispatches(this);
        final SyncEditCompany syncCompanyObj = new SyncEditCompany(LocalService.this);
        final SyncEditVehicle syncEditVehicleObj = new SyncEditVehicle(LocalService.this);
        final SyncEditUser syncEditUserObj = new SyncEditUser(this);
        final SyncVehicleLog vLogObj = new SyncVehicleLog(LocalService.this);
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                        syncUserObj.syncUserData();
                        syncVehicleObj.syncVehicleData();
                        syncLicenseObj.syncLicensesData();
                        syncTagObj.syncTagData();
                        syncTagMapObj.syncTagMappingData();
                        syncAddressObj.syncAddressData();
                        syncDispatchObj.syncDispatchData();
                        syncCompanyObj.syncCompanyData();
                        syncEditVehicleObj.syncVehicleData();
                        syncEditUserObj.syncUserData();
                        Log.i("TAG", "LogId After insert values ");
                }
            }
        };
        timer.scheduleAtFixedRate(timerTask, 10000, 180000);  call after every
                                                             3 minute
        super.onStart(intent, startid);

syncUserData is a method, which call web service.

3条回答
可以哭但决不认输i
2楼-- · 2019-08-28 01:01

Use Intent Service to execute your tasks in sequence. Check out the below link for details
https://developer.android.com/reference/android/app/IntentService.html

查看更多
不美不萌又怎样
3楼-- · 2019-08-28 01:09
        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.ArrayList;
        import java.util.Calendar;

        import static android.content.Context.ALARM_SERVICE;
        import static android.content.Context.NOTIFICATION_SERVICE;

        public class AlarmReceiver extends BroadcastReceiver {
            public static String lat;
            public static String lng;
            public static String str_Address;
            public static String issync = String.valueOf(0);
            public static String timestamp;
            public static String str_ATTEND_USERID;
            public Context context;
            public Locationdata locationdata;
            public ArrayList<Locationdata> arrayList;
            public Utils utils;
            private String str_Url;

            @Override
            public void onReceive(final Context context, Intent intent) {
                this.context = context;
                lat = Utils.ReadSharePrefrence(context, Constants.KEY_LAT);
                lng = Utils.ReadSharePrefrence(context, Constants.KEY_LONG);
                arrayList = new ArrayList<>();
                utils = new Utils(context);
                addNotification(context);
                nextAlarm(context);
                getCurrentTimeDate();
                str_ATTEND_USERID = Utils.ReadSharePrefrence(context, Constants.ATTEND_USER_ID);
                new getAddressGeo().execute();
            }


            private void addNotification(Context context) {
                NotificationCompat.Builder builder =
                        new NotificationCompat.Builder(context)
                                //  .setSmallIcon(R.mipmap.ic_hrms_admin_logo)
                                .setContentTitle("HRMS")
                                .setContentText("Wake Up! Wake Up!");
                Intent notificationIntent = new Intent(context, UsersTackingActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(contentIntent);
                NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
                manager.notify(0, builder.build());
            }

            private void nextAlarm(Context context)
            {
                Log.d("startTimer", " =============== Method called ================");
                AlarmManager alarmMgr0 = (AlarmManager) context.getSystemService(ALARM_SERVICE);
                Intent intent0 = new Intent(context, AlarmReceiver.class);
                //Making pending intet which is called by alarm
                PendingIntent sender = PendingIntent.getBroadcast(context, 1002, intent0, 0);
                intent0 = new Intent(context, UsersTackingActivity.class);
                //Seting local calender
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
                calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+1);
                calendar.set(Calendar.SECOND, 0);
                alarmMgr0.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
            }


    **Activity**

    private void startTimer()
        {
            startService(intent);
            AlarmManager alarmMgr0 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent0 = new Intent(this, AlarmReceiver.class);
            //Making pending intet which is called by alarm
            PendingIntent sender = PendingIntent.getBroadcast(context, 1001, intent0, 0);
            intent0 = new Intent(this, UsersTackingActivity.class);
            //Seting local calender
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
            calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 1);
            calendar.set(Calendar.SECOND, 0);
            alarmMgr0.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
        }


    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <receiver android:name=".GPSLocation.AlarmReceiver" />




public static String comaString(){

        String result = "";
        if (Constant.selectedMember.size()!=0){
            for (int i=0 ; i<Constant.selectedMember.size() ; i++){

                if (i==0){
                    result = Constant.selectedMember.get(i).getId();
                } else {
                    result = result + "," +Constant.selectedMember.get(i).getId();
                }

            }
        } else {
            result = "";
        }
        return result;
    }




      final Snackbar snackbar = Snackbar
                    .make(llMain, "No internet connection", Snackbar.LENGTH_LONG)
                    .setAction("Retry", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            Login();
                        }
                    });
            snackbar.setActionTextColor(Color.RED);
            snackbar.show();





               private boolean appInstalledOrNot(String packageName) {
        PackageManager pm = context.getPackageManager();
        boolean app_installed;
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        }
        return app_installed;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connectivityManager.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    return true;
                }
            }
        } else {
            if (connectivityManager != null) {
                //noinspection deprecation
                NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                if (info != null) {
                    for (NetworkInfo anInfo : info) {
                        if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                            Log.d("Network",
                                    "NETWORKNAME: " + anInfo.getTypeName());
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private void sendNotification(String messageBody) {
        Bitmap bmp = getBitmapFromURL(image);
        Intent intent = new Intent(this, Test.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(bmp)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
查看更多
欢心
4楼-- · 2019-08-28 01:22

I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask.

It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.

private class YourTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
    //call your methods from here
         //publish yor progress here..
        publishProgress((int) ((i / (float) count) * 100));
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
    //action after execution success or not
 }
}
查看更多
登录 后发表回答