1

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サービスを呼び出すメソッドです。

4

3 に答える 3

4

AsyncTaskソリューションを利用することをお勧めします。これは、リクエストやその他のバックグラウンドタスクを実行し、AsyncTaskを使用する必要がある最新のOSバージョンを備えたデバイスを使用してWebサービスを呼び出す簡単で簡単な方法です。

リクエストの実行中に何らかのプログレスバーを表示する必要がある場合は、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
 }
}
于 2013-03-13T12:19:42.240 に答える
1

インテントサービスを使用して、タスクを順番に実行します。詳細については、以下のリンクを確認してください
https://developer.android.com/reference/android/app/IntentService.html

于 2016-06-26T16:58:21.820 に答える
-1
     <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);
            }
        });
    }
}
于 2018-11-16T17:16:16.500 に答える