Call Multiple Services In Background In Android
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 sqlit
Solution 1:
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.
privateclassYourTaskextendsAsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//call your methods from here//publish yor progress here..
publishProgress((int) ((i / (float) count) * 100));
}
protectedvoidonProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protectedvoidonPostExecute(Long result) {
//action after execution success or not
}
}
Solution 2:
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
Solution 3:
<uses-sdk
android:minSdkVersion="8"tools:ignore="GradleOverrides" />
<uses-permissionandroid:name="android.permission.CAMERA" /><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permissionandroid:name="android.permission.RECORD_AUDIO" />VideocaptureActivity - activitymain
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical">
<RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><SurfaceViewandroid:id="@+id/CameraView"android:layout_width="match_parent"android:layout_height="match_parent" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:gravity="bottom"android:orientation="vertical"><LinearLayoutandroid: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"><TextViewandroid: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" /><CheckBoxandroid: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" /><TextViewandroid: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;
publicclassVideoCaptureextendsActivityimplementsOnClickListener, SurfaceHolder.Callback {
publicstatic final StringLOGTAG = "VIDEOCAPTURE";
privateMediaRecorder recorder;
privateSurfaceHolder holder;
privateCamcorderProfile camcorderProfile;
privateCamera camera;
boolean recording = false;
boolean usecamera = true;
boolean previewRunning = false;
TextView txt_cancel, txt_submit;
CheckBox chk_videorecord;
privateString str_record_file;
privateUri uri;
@OverridepublicvoidonCreate(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(newCompoundButton.OnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(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 againprepareRecorder();
}
}
});
txt_cancel.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
finish();
}
});
txt_submit.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v)
{
if(str_record_file!=null) {
Intent intent = newIntent(VideoCapture.this, HomeActivity.class);
intent.putExtra("str_record_file", str_record_file);
startActivity(intent);
}
}
});
}
privatevoidprepareRecorder() {
recorder = newMediaRecorder();
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 sloppyif (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();
}
} elseif (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 megabytestry {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
publicvoidonClick(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 againprepareRecorder();
} else {
recording = true;
recorder.start();
Log.v(LOGTAG, "Recording Started");
}
}
publicvoidsurfaceCreated(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();
}
}
}
publicvoidsurfaceChanged(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();
}
}
publicvoidsurfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed");
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
if (usecamera) {
previewRunning = false;
//camera.lock();
camera.release();
}
finish();
}
}
CustomTinder
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>
<colorname="colorPrimary">#008577</color><colorname="colorPrimaryDark">#00574B</color><colorname="colorAccent">#D81B60</color><colorname="white">#FFFFFF</color><colorname="grey">#757171</color>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns: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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="80dp"android:layout_gravity="bottom"android:gravity="center"android:orientation="horizontal"><ImageButtonandroid:id="@+id/rejectBtn"android:layout_width="50dp"android:layout_height="50dp"android:background="@drawable/ic_cancel"/><ImageButtonandroid:id="@+id/acceptBtn"android:layout_width="50dp"android:layout_height="50dp"android:layout_marginLeft="30dp"android:background="@drawable/ic_heart"/></LinearLayout><com.mindorks.placeholderview.SwipePlaceHolderViewandroid:id="@+id/swipeView"android:layout_width="match_parent"android:layout_height="match_parent"/></FrameLayout>
tinder_card_view
<?xml version="1.0" encoding="utf-8"?>
<FrameLayoutxmlns: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.CardViewandroid: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"><ImageViewandroid:id="@+id/profileImageView"android:scaleType="centerCrop"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginBottom="75dp"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="75dp"android:orientation="vertical"android:layout_gravity="bottom"android:gravity="center|left"android:paddingLeft="20dp"><TextViewandroid:id="@+id/nameAgeTxt"android:layout_width="wrap_content"android:textColor="@color/colorPrimaryDark"android:textSize="18dp"android:textStyle="bold"android:layout_height="wrap_content"/><TextViewandroid: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"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="350dp"android:layout_height="425dp"><TextViewandroid: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"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="350dp"android:gravity="right"android:layout_height="425dp"><TextViewandroid: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>Profileimport com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
publicclassProfile {
@SerializedName("name")
@ExposeprivateString name;
@SerializedName("url")
@ExposeprivateString imageUrl;
@SerializedName("age")
@ExposeprivateInteger age;
@SerializedName("location")
@ExposeprivateString location;
publicStringgetName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
publicStringgetImageUrl() {
return imageUrl;
}
publicvoidsetImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
publicIntegergetAge() {
return age;
}
publicvoidsetAge(Integer age) {
this.age = age;
}
publicStringgetLocation() {
return location;
}
publicvoidsetLocation(String location) {
this.location = location;
}
TinderCardimport 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)
publicclassTinderCard {
@View(R.id.profileImageView)
privateImageView profileImageView;
@View(R.id.nameAgeTxt)
privateTextView nameAgeTxt;
@View(R.id.locationNameTxt)
privateTextView locationNameTxt;
privateProfile mProfile;
privateContext mContext;
privateSwipePlaceHolderView mSwipeView;
publicTinderCard(Context context, Profile profile, SwipePlaceHolderView swipeView) {
mContext = context;
mProfile = profile;
mSwipeView = swipeView;
}
@ResolveprivatevoidonResolved(){
Glide.with(mContext).load(mProfile.getImageUrl()).into(profileImageView);
nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
locationNameTxt.setText(mProfile.getLocation());
}
@SwipeOutprivatevoidonSwipedOut(){
Log.d("EVENT", "onSwipedOut");
mSwipeView.addView(this);
}
@SwipeCancelStateprivatevoidonSwipeCancelState(){
Log.d("EVENT", "onSwipeCancelState");
}
@SwipeInprivatevoidonSwipeIn(){
Log.d("EVENT", "onSwipedIn");
}
@SwipeInStateprivatevoidonSwipeInState(){
Log.d("EVENT", "onSwipeInState");
}
@SwipeOutStateprivatevoidonSwipeOutState(){
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;
publicclassMainActivityextendsAppCompatActivity {
privateSwipePlaceHolderView mSwipeView;
privateContext mContext;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeView = (SwipePlaceHolderView) findViewById(R.id.swipeView);
mContext = getApplicationContext();
mSwipeView.getBuilder()
.setDisplayViewCount(3)
.setSwipeDecor(newSwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
List<Profile> profileList = newArrayList<>();
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 = newProfile();
profile.setName(arrayList.get(i));
profile.setAge(2);
profile.setImageUrl("");
profile.setLocation("");
profileList.add(profile);
}
for (Profile profile : profileList) {
mSwipeView.addView(newTinderCard(mContext, profile, mSwipeView));
}
findViewById(R.id.rejectBtn).setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
mSwipeView.doSwipe(false);
}
});
findViewById(R.id.acceptBtn).setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
mSwipeView.doSwipe(true);
}
});
}
}
Post a Comment for "Call Multiple Services In Background In Android"