【问题标题】:Call multiple services in background in android在android后台调用多个服务
【发布时间】:2013-03-13 11:53:37
【问题描述】:

我必须在后台为 android 应用程序中的项目调用多个服务。 在每个服务中,我必须调用单独的 Web 服务并获取一些数据并使用本地 sqlite 数据库处理它。我可以分别调用每个服务,并可以使用本地数据库操作其结果。 但无法按顺序调用所有服务。 我的代码如下:

@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 是一种调用 Web 服务的方法。

【问题讨论】:

    标签: android service android-service background-process


    【解决方案1】:

    我建议您选择 AsyncTask 解决方案。这是一种运行请求或任何其他后台任务并使用具有最新操作系统版本的设备调用 Web 服务的简单直接的方法,您必须使用 AsyncTask。

    它也很容易实现,例如onProgressUpdate 如果您需要在运行请求时显示某种进度条。

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

    【讨论】:

      【解决方案2】:

      使用 Intent 服务按顺序执行您的任务。 查看以下链接了解详情
      https://developer.android.com/reference/android/app/IntentService.html

      【讨论】:

        【解决方案3】:
             <uses-sdk
                    android:minSdkVersion="8"
                    tools:ignore="GradleOverrides" />
                <uses-permission android:name="android.permission.CAMERA" />
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
                <uses-permission android:name="android.permission.RECORD_AUDIO" />
            Videocapture Activity   - activitymain
        
        
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical">
        
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
        
                    <SurfaceView
                        android:id="@+id/CameraView"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />
        
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:gravity="bottom"
                        android:orientation="vertical">
        
                        <LinearLayout
        
                            android:gravity="center_vertical"
                            android:background="@color/color_transparent"
                            android:paddingLeft="10dp"
                            android:paddingRight="10dp"
                            android:layout_width="match_parent"
                            android:layout_height="150dp"
                            android:orientation="horizontal">
                            <TextView
                                android:id="@+id/txt_cancel"
                                android:layout_width="0dp"
                                android:layout_height="wrap_content"
                                android:text="Cancel"
                                android:layout_weight="1"
                                android:textSize="30dp"
                                android:textColor="@color/color_white" />
        
                            <CheckBox
                                android:button="@drawable/checkbox"
                                android:id="@+id/chk_videorecord"
                                android:layout_width="100dp"
                                android:layout_height="100dp"
                                android:textColor="@color/color_white"
                                android:textOff="@null"
                                android:textOn="@null" />
        
                            <TextView
                                android:id="@+id/txt_submit"
                                android:layout_weight="1"
                                android:layout_width="0dp"
                                android:layout_height="wrap_content"
                                android:text="Submit"
                                android:textSize="30dp"
                                android:textColor="@color/color_white" />
        
                        </LinearLayout>
        
                    </LinearLayout>
                </RelativeLayout>
            </LinearLayout>
        
        
        
        
        
            import java.io.File;
            import java.io.IOException;
        
            import android.app.Activity;
            import android.content.Intent;
            import android.hardware.Camera;
            import android.media.CamcorderProfile;
            import android.media.MediaRecorder;
            import android.net.Uri;
            import android.os.Bundle;
            import android.os.Environment;
            import android.util.Log;
            import android.view.SurfaceHolder;
            import android.view.SurfaceView;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.widget.Button;
            import android.widget.CheckBox;
            import android.widget.CompoundButton;
            import android.widget.MediaController;
            import android.widget.TextView;
            import android.widget.Toast;
            import android.widget.ToggleButton;
            import android.widget.VideoView;
        
            public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
        
                public static final String LOGTAG = "VIDEOCAPTURE";
        
                private MediaRecorder recorder;
                private SurfaceHolder holder;
                private CamcorderProfile camcorderProfile;
                private Camera camera;
        
                boolean recording = false;
                boolean usecamera = true;
                boolean previewRunning = false;
        
                TextView txt_cancel, txt_submit;
                CheckBox chk_videorecord;
                private String str_record_file;
                private Uri uri;
        
                @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
                    setContentView(R.layout.activity_main);
                    chk_videorecord = findViewById(R.id.chk_videorecord);
                    final SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
                    txt_cancel = findViewById(R.id.txt_cancel);
                    txt_submit = findViewById(R.id.txt_submit);
                    holder = cameraView.getHolder();
                    holder.addCallback(this);
                    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        
                    cameraView.setClickable(true);
                    cameraView.setOnClickListener(this);
        
                    chk_videorecord.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            if (chk_videorecord.isChecked())
                            {
                                chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_stop_record));
                                recording = true;
                                recorder.start();
                                Toast.makeText(VideoCapture.this, "Recording Started", Toast.LENGTH_SHORT).show();
        
                            } else {
                                chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_start_record));
                                recorder.stop();
                                Toast.makeText(VideoCapture.this, "Recording Stop", Toast.LENGTH_SHORT).show();
                                if (usecamera) {
                                    try {
                                        camera.reconnect();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                // recorder.release();
                                recording = false;
                                Log.v(LOGTAG, "Recording Stopped");
                                // Let's prepareRecorder so we can record again
                                prepareRecorder();
                            }
                        }
                    });
        
        
                    txt_cancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
        
        
                    txt_submit.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v)
                        {
                            if(str_record_file!=null) {
                                Intent intent = new Intent(VideoCapture.this, HomeActivity.class);
                                intent.putExtra("str_record_file", str_record_file);
                                startActivity(intent);
                            }
                        }
                    });
                }
        
                private void prepareRecorder() {
                    recorder = new MediaRecorder();
                    recorder.setPreviewDisplay(holder.getSurface());
        
                    if (usecamera) {
                        camera.unlock();
                        recorder.setCamera(camera);
                    }
        
                    recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
                    recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        
                    recorder.setProfile(camcorderProfile);
        
                    // This is all very sloppy
                    if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.THREE_GPP)
                    {
                        try {
                            File newFile = File.createTempFile("videocapture", ".3gp", Environment.getExternalStorageDirectory());
                            recorder.setOutputFile(newFile.getAbsolutePath());
                            str_record_file = newFile.getAbsolutePath();
                            Log.d("file_path", "=======>" + str_record_file);
        
                        } catch (IOException e) {
                            Log.v(LOGTAG, "Couldn't create file");
                            e.printStackTrace();
                            finish();
                        }
                    } else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
                        try {
                            File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
                            recorder.setOutputFile(newFile.getAbsolutePath());
                            str_record_file = newFile.getAbsolutePath();
                            Log.d("file_path", "=======>" + str_record_file);
        
                        } catch (IOException e) {
                            Log.v(LOGTAG, "Couldn't create file");
                            e.printStackTrace();
                            finish();
                        }
                    } else {
                        try {
                            File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
                            recorder.setOutputFile(newFile.getAbsolutePath());
                            str_record_file = newFile.getAbsolutePath();
                            Log.d("file_path", "=======>" + str_record_file);
        
                        } catch (IOException e) {
                            Log.v(LOGTAG, "Couldn't create file");
                            e.printStackTrace();
                            finish();
                        }
        
                    }
                    //recorder.setMaxDuration(50000); // 50 seconds
                    //recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
        
                    try {
                        recorder.prepare();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                        finish();
                    } catch (IOException e) {
                        e.printStackTrace();
                        finish();
                    }
                }
        
                public void onClick(View v) {
                    if (recording) {
                        recorder.stop();
                        if (usecamera) {
                            try {
                                camera.reconnect();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        // recorder.release();
                        recording = false;
                        Log.v(LOGTAG, "Recording Stopped");
                        // Let's prepareRecorder so we can record again
                        prepareRecorder();
                    } else {
                        recording = true;
                        recorder.start();
                        Log.v(LOGTAG, "Recording Started");
                    }
                }
        
                public void surfaceCreated(SurfaceHolder holder) {
                    Log.v(LOGTAG, "surfaceCreated");
        
                    if (usecamera) {
                        camera = Camera.open();
        
                        try {
                            camera.setPreviewDisplay(holder);
                            camera.startPreview();
                            previewRunning = true;
                        } catch (IOException e) {
                            Log.e(LOGTAG, e.getMessage());
                            e.printStackTrace();
                        }
                    }
        
                }
        
        
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    Log.v(LOGTAG, "surfaceChanged");
        
                    if (!recording && usecamera) {
                        if (previewRunning) {
                            camera.stopPreview();
                        }
        
                        try {
                            Camera.Parameters p = camera.getParameters();
        
                            p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
                            p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
        
                            camera.setParameters(p);
        
                            camera.setPreviewDisplay(holder);
                            camera.startPreview();
                            previewRunning = true;
                        } catch (IOException e) {
                            Log.e(LOGTAG, e.getMessage());
                            e.printStackTrace();
                        }
        
                        prepareRecorder();
                    }
                }
        
        
                public void surfaceDestroyed(SurfaceHolder holder) {
                    Log.v(LOGTAG, "surfaceDestroyed");
                    if (recording) {
                        recorder.stop();
                        recording = false;
                    }
                    recorder.release();
                    if (usecamera) {
                        previewRunning = false;
                        //camera.lock();
                        camera.release();
                    }
                    finish();
                }
            }
        
        
        
        
        Custom Tinder
        
         implementation 'com.mindorks:placeholderview:0.7.1'
            implementation 'com.android.support:cardview-v7:25.3.1'
            implementation 'com.github.bumptech.glide:glide:3.7.0'
            implementation 'com.google.code.gson:gson:2.7'
        
             <string-array name="arry_card">
                    <item>Sofia</item>
                <item>Roma</item>
                <item>Zoya</item>
            </string-array>
        
              <color name="colorPrimary">#008577</color>
            <color name="colorPrimaryDark">#00574B</color>
            <color name="colorAccent">#D81B60</color>
            <color name="white">#FFFFFF</color>
            <color name="grey">#757171</color>
        
            activity_main
        
            <?xml version="1.0" encoding="utf-8"?>
        <FrameLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/grey">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:layout_gravity="bottom"
                android:gravity="center"
                android:orientation="horizontal">
                <ImageButton
                    android:id="@+id/rejectBtn"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="@drawable/ic_cancel"/>
                <ImageButton
                    android:id="@+id/acceptBtn"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginLeft="30dp"
                    android:background="@drawable/ic_heart"/>
            </LinearLayout>
            <com.mindorks.placeholderview.SwipePlaceHolderView
                android:id="@+id/swipeView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
        </FrameLayout>
        
        
        tinder_card_view
        
        <?xml version="1.0" encoding="utf-8"?>
        <FrameLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="350dp"
            android:layout_height="425dp"
            android:layout_marginBottom="50dp"
            android:orientation="vertical">
            <android.support.v7.widget.CardView
                android:orientation="vertical"
                android:background="@color/white"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
                app:cardCornerRadius="7dp"
                app:cardElevation="4dp">
                <ImageView
                    android:id="@+id/profileImageView"
                    android:scaleType="centerCrop"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginBottom="75dp"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="75dp"
                    android:orientation="vertical"
                    android:layout_gravity="bottom"
                    android:gravity="center|left"
                    android:paddingLeft="20dp">
                    <TextView
                        android:id="@+id/nameAgeTxt"
                        android:layout_width="wrap_content"
                        android:textColor="@color/colorPrimaryDark"
                        android:textSize="18dp"
                        android:textStyle="bold"
                        android:layout_height="wrap_content"/>
                    <TextView
                        android:id="@+id/locationNameTxt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorPrimaryDark"
                        android:textSize="14dp"
                        android:textStyle="normal"/>
                </LinearLayout>
            </android.support.v7.widget.CardView>
        </FrameLayout>
        
        tinder_swipe_in_msg_view
        
        
        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="350dp"
            android:layout_height="425dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="32sp"
                android:textStyle="bold"
                android:layout_margin="40dp"
                android:textColor="@android:color/holo_green_light"
                android:text="Accept"/>
        </LinearLayout>
        
        
        tinder_swipe_out_msg_view
        
        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="350dp"
            android:gravity="right"
            android:layout_height="425dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="32sp"
                android:textStyle="bold"
                android:layout_margin="40dp"
                android:textColor="@android:color/holo_red_light"
                android:text="Reject"/>
        </LinearLayout>
        
        
        
        Profile
        
        import com.google.gson.annotations.Expose;
        import com.google.gson.annotations.SerializedName;
        
        public class Profile {
        
            @SerializedName("name")
            @Expose
            private String name;
        
            @SerializedName("url")
            @Expose
            private String imageUrl;
        
            @SerializedName("age")
            @Expose
            private Integer age;
        
            @SerializedName("location")
            @Expose
            private String location;
        
            public String getName() {
                return name;
            }
        
            public void setName(String name) {
                this.name = name;
            }
        
            public String getImageUrl() {
                return imageUrl;
            }
        
            public void setImageUrl(String imageUrl) {
                this.imageUrl = imageUrl;
            }
        
            public Integer getAge() {
                return age;
            }
        
            public void setAge(Integer age) {
                this.age = age;
            }
        
            public String getLocation() {
                return location;
            }
        
            public void setLocation(String location) {
                this.location = location;
            }
        
        
        
            TinderCard
        
        import android.content.Context;
        import android.util.Log;
        import android.widget.ImageView;
        import android.widget.TextView;
        
        import com.bumptech.glide.Glide;
        import com.mindorks.placeholderview.SwipePlaceHolderView;
        import com.mindorks.placeholderview.annotations.Layout;
        import com.mindorks.placeholderview.annotations.Resolve;
        import com.mindorks.placeholderview.annotations.View;
        import com.mindorks.placeholderview.annotations.swipe.SwipeCancelState;
        import com.mindorks.placeholderview.annotations.swipe.SwipeIn;
        import com.mindorks.placeholderview.annotations.swipe.SwipeInState;
        import com.mindorks.placeholderview.annotations.swipe.SwipeOut;
        import com.mindorks.placeholderview.annotations.swipe.SwipeOutState;
        
        @Layout(R.layout.tinder_card_view)
        public class TinderCard {
        
            @View(R.id.profileImageView)
            private ImageView profileImageView;
        
            @View(R.id.nameAgeTxt)
            private TextView nameAgeTxt;
        
            @View(R.id.locationNameTxt)
            private TextView locationNameTxt;
        
            private Profile mProfile;
            private Context mContext;
            private SwipePlaceHolderView mSwipeView;
        
            public TinderCard(Context context, Profile profile, SwipePlaceHolderView swipeView) {
                mContext = context;
                mProfile = profile;
                mSwipeView = swipeView;
            }
        
            @Resolve
            private void onResolved(){
                Glide.with(mContext).load(mProfile.getImageUrl()).into(profileImageView);
                nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
                locationNameTxt.setText(mProfile.getLocation());
            }
        
            @SwipeOut
            private void onSwipedOut(){
                Log.d("EVENT", "onSwipedOut");
                mSwipeView.addView(this);
            }
        
            @SwipeCancelState
            private void onSwipeCancelState(){
                Log.d("EVENT", "onSwipeCancelState");
            }
        
            @SwipeIn
            private void onSwipeIn(){
                Log.d("EVENT", "onSwipedIn");
            }
        
            @SwipeInState
            private void onSwipeInState(){
                Log.d("EVENT", "onSwipeInState");
            }
        
            @SwipeOutState
            private void onSwipeOutState(){
                Log.d("EVENT", "onSwipeOutState");
            }
        }
        
        
        
        
        
        import android.content.Context;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        
        import com.google.gson.Gson;
        import com.mindorks.placeholderview.SwipeDecor;
        import com.mindorks.placeholderview.SwipePlaceHolderView;
        
        import java.util.ArrayList;
        import java.util.Arrays;
        import java.util.List;
        
        public class MainActivity extends AppCompatActivity {
        
            private SwipePlaceHolderView mSwipeView;
            private Context mContext;
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        
                mSwipeView = (SwipePlaceHolderView) findViewById(R.id.swipeView);
                mContext = getApplicationContext();
        
                mSwipeView.getBuilder()
                        .setDisplayViewCount(3)
                        .setSwipeDecor(new SwipeDecor()
                                .setPaddingTop(20)
                                .setRelativeScale(0.01f)
                                .setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
                                .setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
        
        
                List<Profile> profileList = new ArrayList<>();
        
                List<String> arrayList = Arrays.asList(getResources().getStringArray(R.array.arry_card));
                for (int i = 0; i < arrayList.size(); i++) {
                    //Profile profile = Gson.fromJson(arrayList.get(i), Profile.class);
                    Profile profile = new Profile();
                    profile.setName(arrayList.get(i));
                    profile.setAge(2);
                    profile.setImageUrl("");
                    profile.setLocation("");
                    profileList.add(profile);
                }
        
                for (Profile profile : profileList) {
                    mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
                }
        
                findViewById(R.id.rejectBtn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSwipeView.doSwipe(false);
                    }
                });
        
                findViewById(R.id.acceptBtn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSwipeView.doSwipe(true);
                    }
                });
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-28
          • 2016-09-04
          • 1970-01-01
          相关资源
          最近更新 更多