I have an IntentService to upload images to server (source below). While upload is in progress, user might select more images to upload. Right now it spawns another service. How can I add data to same running service or spawn new service if its not running
public class UploadService extends IntentService {
public static final String TAG = UploadService.class.getSimpleName();
public static final String ACTION_UPLOAD = UploadService.class.getName() + ".UPLOAD";
public static final String EXTRA_RESOURCE_ID = "resource_id";
public static final String EXTRA_RESOURCE_NAME = "resource_name";
public static final String EXTRA_IMAGES = "images";
private static final int CONCURRRENT_UPLOAD_COUNT = 3;
private static final int UPLOAD_STATUS_PENDING = 0;
private static final int UPLOAD_STATUS_UPLOADING = 1;
private static final int UPLOAD_STATUS_UPLOADED = 2;
private static final int UPLOAD_STATUS_FAILED = 3;
private static final int UPLOAD_STATUS_TERMINATED = 4;
private ArrayList<DiskImage> mImages = new ArrayList<>();
private ArrayMap<DiskImage, Integer> mStatusMap = new ArrayMap<>();
private OkHttpClient mOkHttpClient = new OkHttpClient();
public UploadService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction().equals(ACTION_UPLOAD)) {
String resId = intent.getStringExtra(EXTRA_RESOURCE_ID);
String resName = intent.getStringExtra(EXTRA_RESOURCE_NAME);
ArrayList<DiskImage> images = intent.getParcelableArrayListExtra(EXTRA_IMAGES);
for (DiskImage image : images) {
image.mUploadId = resId;
image.mUploadResName = resName;
}
mImages.addAll(images);
upload(); // start the upload
updateNotification();
}
}
private int getUploadedImageCount() {
int count = 0;
for (int i = 0; i < mImages.size(); i++)
if (getStatus(mImages.get(i)) == UPLOAD_STATUS_UPLOADED)
count++;
return count;
}
private void updateNotification() {
UploadNotification.notify(UploadService.this, mImages.size(), getUploadedImageCount());
}
private void upload() {
final DiskImage image = getImageToUpload();
if (image != null) {
// show notification
MediaType mediaType = MediaType.parse(image.mimeType);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("resource_id", image.mUploadId)
.addFormDataPart("resource_name", image.mUploadResName)
.addFormDataPart("image", getName(image.path),
RequestBody.create(mediaType, new File(image.path)))
.build();
Request request = new Request.Builder()
.url(getUploadUrl())
.post(requestBody)
.build();
mStatusMap.put(image, UPLOAD_STATUS_UPLOADING);
// Log.i(TAG, "Uploading image " + getName(image.path));
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
mStatusMap.put(image, UPLOAD_STATUS_FAILED);
// add failed image in end
mImages.remove(image);
mImages.add(image);
// Log.i(TAG, "Upload failed " + getName(image.path));
upload();
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// Log.i(TAG, "Uploaded image " + getName(image.path) + " Response: " + response.body().string());
mStatusMap.put(image, UPLOAD_STATUS_UPLOADED);
upload(); // upload next image
updateNotification();
}
});
}
}
private String getName(String path) {
return path.substring(path.lastIndexOf(File.separator) + 1, path.length());
}
private DiskImage getImageToUpload() {
for (int i = 0; i < mImages.size(); i++)
if (getStatus(mImages.get(i)) == UPLOAD_STATUS_PENDING)
return mImages.get(i);
return null;
}
private String getUploadUrl() {
return String.format(Constants.ALBUM_IMAGE_UPLOAD_URL, Preferences.getToken(this));
}
private int getStatus(DiskImage image) {
if (mStatusMap.get(image) == null)
return UPLOAD_STATUS_PENDING;
return mStatusMap.get(image);
}
}
Couldn't you just extend Service (not IntentService), bind your Activity to the Service and then call a method of this Service, that does the upload of the picture.
In this way, your service will run until you call stopSelf() in the service or stopService() in your bounded activity. Hence, you could use the same service to do multiple uploads.
Please let me know if this answer helped a bit...
Related
I'm trying to use RETROFIT to get an inform about COVID-19 data. And I want to show the latest data, so I tried
content1 = covid_post_data.getPositive() + "\n";
content2 = covid_post_data.getDeath() + "\n";
content3 = " (+" + covid_post_data.getPositiveIncrease() + ")\n";
content4 = " (+" + covid_post_data.getDeathIncrease() + ")\n";
content5 = " Updated : " + covid_post_data.getDate() + "\n";
textViewResult.setText(content1);
textViewResult2.setText(content2);
textViewResult3.setText(content3);
textViewResult4.setText(content4);
textViewResult5.setText(content5);
But it is not working.it didn't show any data. how can i show the latest data in JSON file with using retrofit? below is my whole code of main activity
1.MainActivity
public class COVIDActivity extends AppCompatActivity {
private TextView textViewResult;
private TextView textViewResult2;
private TextView textViewResult3;
private TextView textViewResult4;
private TextView textViewResult5;
private static final String TAG = "COVIDActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.covid_menu);
//How go_back_button works
ImageButton bo_back_Button = (ImageButton) findViewById(R.id.covid_to_main);
bo_back_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent move_main_covid = new Intent(COVIDActivity.this,MainActivity.class);
startActivity(move_main_covid);
}
});
textViewResult = findViewById(R.id.text_view_result_positive);
textViewResult2 = findViewById(R.id.text_view_result_death);
textViewResult3 = findViewById(R.id.text_view_result_positive_increase);
textViewResult4 = findViewById(R.id.text_view_result_death_increase);
textViewResult5 = findViewById(R.id.today_date);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://covidtracking.com/api/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<COVID_Post_Data>> call = jsonPlaceHolderApi.get_covid_post();
call.enqueue(new Callback<List<COVID_Post_Data>>() {
#Override
public void onResponse(Call<List<COVID_Post_Data>> call, Response<List<COVID_Post_Data>> response) {
if (!response.isSuccessful()) {
textViewResult.setText(("Code: " + response.code()));
return;
}
List<COVID_Post_Data> posts = response.body();
//Give message if fail, TAG is COVIDActivity so that it will show log in this activity
if(posts == null) {
Log.w(TAG,"Did not receive any valid response body");
return;
}
for (COVID_Post_Data covid_post_data : posts) {
String content1,content2,content3,content4,content5 = "";
content1 = covid_post_data.getPositive() + "\n";
content2 = covid_post_data.getDeath() + "\n";
content3 = " (+" + covid_post_data.getPositiveIncrease() + ")\n";
content4 = " (+" + covid_post_data.getDeathIncrease() + ")\n";
content5 = " Updated : " + covid_post_data.getDate() + "\n";
textViewResult.append(content1);
textViewResult2.append(content2);
textViewResult3.append(content3);
textViewResult4.append(content4);
textViewResult5.append(content5);
}
}
2.get JSON file
public interface JsonPlaceHolderApi {
//get data from json about US infection
#GET("us/daily.json")
Call<List<COVID_Post_Data>> get_covid_post();
//get data from json about states infection
#GET("states/daily.json")
Call<List<COVID_Post_Data>> get_covid_post_state();
}
3.getter function
public class COVID_Post_Data {
private String dataChecked;
private int positiveIncrease;
private int negativeIncrease;
private int deathIncrease;
private String state;
private int positive;
private int death;
private int date;
//if the variable is matched with name in json file no need to put #SerializedName here
public String getDataChecked() {
return dataChecked;
}
public int getPositiveIncrease() {
return positiveIncrease;
}
public int getNegativeIncrease() {
return negativeIncrease;
}
public int getDeathIncrease() {
return deathIncrease;
}
public String getState() {
return state;
}
public int getPositive() {
return positive;
}
public int getDeath() { return death; }
public int getDate() {
return date;
}
}
I have three activities, I capture all data but one from DetailActivity upon button click and save in database using Room; My intention is to insert all these data into the database and start ReviewActivity so as to get the arraylist of reviews and also insert it in the database. Everything seems to work fine until when I want to view review offline because I believe it has been saved, reviews does not get loaded.
This is my DetailActivity,
TextView overview_tv; ImageView image_tv; TextView name_tv; TextView ratings; Context context; TextView release_date; ImageView backdrop_poster; private ExpandableHeightListView trailers; public static ArrayList<Youtube> youtube; public static ArrayList<Review> reviews; TrailerViewAdapter adapter; public static DataObject data; DataObject dataObject; ArrayList<Review> savedReview; private static final String IMAGE_URL = "http://image.tmdb.org/t/p/w185/"; private static final String THE_MOVIEDB_URL2 = "https://api.themoviedb.org/3/movie/"; private static final String MOVIE_QUERY2 = "api_key"; private static final String API_KEY2 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY2 = "videos"; public static int movieId; Button viewReviews; Button favourite; String movieRating; private static final int YOUTUBE_SEARCH_LOADER = 23; private static final int REVIEW_SEARCH_LOADER = 24; File file; String name; String overview; String releaseDate; int switcher; public static ArrayList<Review> favouriteReviews; TextView trev; AppDatabase mDb; //Navigation arrow on the action bar #Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mDb = AppDatabase.getInstance(getApplicationContext()); youtube = new ArrayList<Youtube>(); reviews = new ArrayList<Review>(); adapter = new TrailerViewAdapter(this, youtube); //Credit to Paolorotolo #github trailers = findViewById(R.id.expandable_list); trailers.setAdapter(adapter); trailers.setExpanded(true); //Navigation arrow on the acton bar; check also override onOptionsItemSelected ActionBar actionBar = this.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } context = getApplicationContext(); Intent intent = getIntent(); if (intent == null) { closeOnError(); } switcher = getIntent().getIntExtra("switch", 3); overview_tv = findViewById(R.id.overview); image_tv = findViewById(R.id.image); name_tv = findViewById(R.id.name); ratings = findViewById(R.id.ratings); release_date = findViewById(R.id.release_date); backdrop_poster = findViewById(R.id.backdrop_poster); trev = findViewById(R.id.review_show); viewReviews = findViewById(R.id.review_button); favourite = findViewById(R.id.favourite_button); addListenerOnRatingBar(ratings); if (switcher != 2) { favourite.setVisibility(View.INVISIBLE); dataObject = (DataObject) getIntent().getParcelableExtra("array"); final String favouriteName = dataObject.getName(); final String favouriteOverview = dataObject.getOverview(); final String favouriteReleaseDate = dataObject.getReleaseDate(); ArrayList<Youtube> savedTrailer = dataObject.getTrailers(); savedReview = dataObject.getMovieReviews(); movieRating = dataObject.getRating(); name_tv.setText(favouriteName); overview_tv.setText(favouriteOverview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + favouriteReleaseDate);// Toast.makeText(this, "Testing Reviews " + savedReview.get(0).getAuthor(), Toast.LENGTH_SHORT).show(); String imagePath = name_tv.getText().toString() + "0i"; String backdropPath = name_tv.getText().toString() + "1b"; try { DataObjectAdapter.downloadImage(imagePath, image_tv, this); } catch (Exception e) { e.printStackTrace(); } try { DataObjectAdapter.downloadImage(backdropPath, backdrop_poster, context); } catch (Exception e) { e.printStackTrace(); } if (savedTrailer != null) { TrailerViewAdapter lv = new TrailerViewAdapter(DetailActivity.this, savedTrailer); trailers.setAdapter(lv); switcher = 3; } } else { name = getIntent().getStringExtra("Name"); overview = getIntent().getStringExtra("Overview"); final String image = getIntent().getStringExtra("Image"); movieId = getIntent().getIntExtra("movieId", 1); final String backdrop = getIntent().getStringExtra("backdrop"); releaseDate = getIntent().getStringExtra("releaseDate"); movieRating = getIntent().getStringExtra("rating"); Log.i("this", "switch " + switcher); name_tv.setText(name); overview_tv.setText(overview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + releaseDate); //load backdrop poster Picasso.with(context) .load(IMAGE_URL + backdrop) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(backdrop_poster); Picasso.with(context) .load(IMAGE_URL + image) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(image_tv); getSupportLoaderManager().initLoader(YOUTUBE_SEARCH_LOADER, null, this); //getSupportLoaderManager().initLoader(REVIEW_SEARCH_LOADER, null, this); //loadTrailers(); //loadReviews(); //populateKeys(); } /** * Here manages the views(list) for reviews */ viewReviews.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if (switcher == 3) { startActivity(new Intent(DetailActivity.this, ReviewActivity.class) .putExtra("switch", 3)); } else { Log.i("this", "I am from initial" + switcher); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId)); } } } ); favourite.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { data = new DataObject(); data.setName(name); data.setOverview(overview); data.setRating(movieRating); data.setReleaseDate(releaseDate); data.setTrailers(youtube);// data.setMovieReviews(reviews); try { saveImage(name_tv.getText().toString() + "0i", image_tv); saveImage(name_tv.getText().toString() + "1b", backdrop_poster); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(context, "The movie is saved as a favourite", Toast.LENGTH_LONG).show(); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { mDb.dataDao().insertData(data); } }); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId) .putExtra(ReviewActivity.EXTRA_DATA_ID, 20)); } } ); }
And my ReviewActivity
public class ReviewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<Review>>{ public static ArrayList<Review> reviews; public static List<DataObject> favouriteReviews; public static RecyclerView reviewList; ArrayList<Review> r; private static final int REVIEW_SEARCH_LOADER = 24; private static final String MOVIE_QUERY3 = "api_key"; private static final String API_KEY3 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY3 = "reviews"; private static final String THE_MOVIEDB_URL3 = "https://api.themoviedb.org/3/movie/"; private static int movId; public static final String EXTRA_DATA_ID = "extraDataId"; private static final int DEFAULT_TASK_ID = -1; private int mTaskId = DEFAULT_TASK_ID; DataObject data1; AppDatabase mDb; ReviewAdapter revAdapter; int loaderSwitch; #Override protected void onResume() { super.onResume(); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); mDb = AppDatabase.getInstance(getApplicationContext()); reviews = new ArrayList<Review>(); favouriteReviews = new ArrayList<DataObject>(); reviewList = findViewById(R.id.review_list); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); reviewList.setLayoutManager(layoutManager); reviewList.setHasFixedSize(true); int switcher = getIntent().getIntExtra("switch", 1); Intent intent = getIntent(); if (intent == null) { finish(); } Log.i("this", "swithcer " + switcher); Log.i("this loader", "Loader " + loaderSwitch); if (switcher == 3){ DataObject dataObject = (DataObject) getIntent().getParcelableExtra("ArrayOfReviews"); if (dataObject != null){ ArrayList<Review> movieReviews = dataObject.getMovieReviews(); Toast.makeText(this, "There are reviews saved", Toast.LENGTH_LONG).show(); revAdapter = new ReviewAdapter(this, movieReviews ); reviewList.setAdapter(revAdapter); } } else { movId = getIntent().getIntExtra("id", 20); revAdapter = new ReviewAdapter(this, reviews); reviewList.setAdapter(revAdapter); loadReviews(); //populateReview(); } DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL); reviewList.addItemDecoration(decoration); } #Override protected void onStart() { super.onStart(); //loadReviews(); } public static URL buildUrl3(String stringUrl) { Uri uri = Uri.parse(THE_MOVIEDB_URL3).buildUpon() .appendPath(stringUrl) .appendPath(SEARCH_QUERY3) .appendQueryParameter(MOVIE_QUERY3, API_KEY3) .build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException exception) { Log.e(TAG, "Error creating URL", exception); } return url; } public void loadReviews(){ // COMPLETED (19) Create a bundle called queryBundle Bundle queryBundle = new Bundle(); // COMPLETED (20) Use putString with SEARCH_QUERY_URL_EXTRA as the key and the String value of the URL as the value// queryBundle.putString(SEARCH_QUERY_URL_EXTRA, url.toString()); // COMPLETED (21) Call getSupportLoaderManager and store it in a LoaderManager variable LoaderManager loaderManager = getSupportLoaderManager(); // COMPLETED (22) Get our Loader by calling getLoader and passing the ID we specified Loader<ArrayList<Review>> movieReviews = loaderManager.getLoader(REVIEW_SEARCH_LOADER); // COMPLETED (23) If the Loader was null, initialize it. Else, restart it. if (movieReviews == null) { loaderManager.initLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } else { loaderManager.restartLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } } #Override public Loader<ArrayList<Review>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<ArrayList<Review>>(this) { #Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } #Override public ArrayList<Review> loadInBackground() { String g = String.valueOf(movId); // Create URL object URL url = buildUrl3(g); // Perform HTTP request on the URL and receive a JSON response back String jsonResponse = ""; try { jsonResponse = getResponseFromHttpUrl(url); } catch (Exception e) { e.printStackTrace(); } reviews = MovieJsonUtils.parseReview(jsonResponse); return reviews; } }; } #Override public void onLoadFinished(Loader<ArrayList<Review>> loader, ArrayList<Review> dat) { if (reviews != null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_DATA_ID)) { //mButton.setText(R.string.update_button); if (mTaskId == DEFAULT_TASK_ID) { mTaskId = intent.getIntExtra(EXTRA_DATA_ID, DEFAULT_TASK_ID); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { data.setMovieReviews(reviews); mDb.dataDao().updateData(data); //mDb.dataDao().insertData(data); final List<DataObject> task = mDb.dataDao().loadById(mTaskId); runOnUiThread(new Runnable() { #Override public void run() { populateUI(task); } }); } }); } } else { ReviewAdapter lv = new ReviewAdapter(ReviewActivity.this, reviews); reviewList.setAdapter(lv); } } } #Override public void onLoaderReset(Loader<ArrayList<Review>> loader) { }
Data gets loaded from MainActivity, the saved data is passed on to other activities as a parcellable bundle via intent, the passed data is displayed in DetailActivity but not in ReviewActivity.
Alternatively, if I can load reviews alongside YouTube keys from DetailActivity, I believe I can handle the database issue from there, but two Loaders wouldn't just work together, the app crashes; I am aware two AsyncTasks concurrently run together solved this problem, but I prefer to use Loaders because of performance on configuration change
I'm developing chat app using XMPP (SAMCK).I have showed conversation using reclycerview. I want to show percentage while image uploading to server(using rest api). So I used intentservice and update the percentage through localbroastreceiver. But I couldn't able to scroll the reclycerview. also I couldn't able to show percentage over image.
Please give comments.
ProgressRequestBody.java
To get percentage I have used this class.
public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private String stanzaId;
private UploadCallbacks mListener;
private static final int DEFAULT_BUFFER_SIZE = 2048;
public interface UploadCallbacks {
void onProgressUpdate(int percentage,String StandzId);
void onError();
void onFinish();
}
public ProgressRequestBody(final File file, String stanzaID, final UploadCallbacks listener) {
mFile = file;
mListener = listener;
this.stanzaId=stanzaID;
}
#Override
public MediaType contentType() {
// i want to upload only images
return MediaType.parse("image/*");
}
#Override
public long contentLength() throws IOException {
return mFile.length();
}
#Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = mFile.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(mFile);
long uploaded = 0;
try {
int read;
Handler handler = new Handler(Looper.getMainLooper());
while ((read = in.read(buffer)) != -1) {
// update progress on UI thread
handler.post(new ProgressUpdater(uploaded, fileLength,stanzaId));
uploaded += read;
sink.write(buffer, 0, read);
}
} finally {
in.close();
}
}
private class ProgressUpdater implements Runnable {
private long mUploaded;
private String mStandzId;
private long mTotal;
public ProgressUpdater(long uploaded, long total,String standzId) {
mUploaded = uploaded;
mTotal = total;
mStandzId=standzId;
}
#Override
public void run() {
mListener.onProgressUpdate((int)(100 * mUploaded / mTotal),mStandzId);
}
}
}
updateservice.class
This is used to call api in background.
public class UploadService extends IntentService implements ProgressRequestBody.UploadCallbacks {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "com.techno.chat_sdk.utilz.action.FOO";
private static final String ACTION_BAZ = "com.techno.chat_sdk.utilz.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.techno.chat_sdk.utilz.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.techno.chat_sdk.utilz.extra.PARAM2";
public UploadService() {
super("UploadService");
}
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* #see IntentService
*/
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, UploadService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* #see IntentService
*/
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
Intent intent = new Intent(context, UploadService.class);
intent.setAction(ACTION_BAZ);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
/*final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFoo(param1, param2);
} else if (ACTION_BAZ.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionBaz(param1, param2);
}*/
Download Download = intent.getParcelableExtra("Download");
File file=new File(Download.getDestinationpath());
ProgressRequestBody fileBody = new ProgressRequestBody(file,Download.getStandzId(), UploadService.this);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody);
FileUpandDown mEdit = ApiConfiguration.getInstance().getApiBuilder().create(FileUpandDown.class);
final Call<JsonObject> request = mEdit.Fileupload(filePart);
request.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.body()!=null){
String url=response.body().get("file_url").getAsString();
if(url!=null){
if (Commonclass.isNetworkConnected(UploadService.this)){
/*json.items.get(0).url=url; // update url to json.
json.items.set(0,items);
duce_Xmppservice.sendMessage(juid, gson.toJson(json), message, false);*/}
}
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
System.out.println("Failure" + t.toString());
}
});
}
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo(String param1, String param2) {
// TODO: Handle action Foo
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz(String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onProgressUpdate(int percentage, String StandzId) {
ContentValues values = new ContentValues();
values.put(DataHelper.CHAT_Msg_DownOrUpPercentage, percentage);
MyApplication.writable.update(DataHelper.CHAT_TABLE_NAME, values, DataHelper.CHAT_Msg_StanzaId + " = ?",
new String[]{StandzId});
Intent intent = new Intent(Constants.ProgreessUpdate);
LocalBroadcastManager.getInstance(MyApplication.getAppContext()).sendBroadcast(intent);
}
#Override
public void onError() {
}
#Override
public void onFinish() {
}
}
singlechatActivity.java (udpate data to list from ocalbroastreceiver)
for(ChatMessages chatMess: section.chatMessages){
if(chatMess.StanzaId.equals(StandzId)){
chatMess.DownUpPercentage=percentage;
section.chatMessages.set(i,chatMess);
strickyAdapter.notifySectionItemChanged(j,i);
}
i++;
}
//StrickyAdapter
switch (jsonMaking.Messagetype){
case "text":
ivh.outgoing_msg.setText(jsonMaking.items.get(0).Body);
ivh.outgoing_Time.setText(Commonclass.GetTime(chat.dateTime));
//set tick status for txt
if(chat.offlinestatus==1){
ivh.tick_status.setImageResource(R.drawable.offlinestatus);
}else if(chat.Deliverystatus==1){
ivh.tick_status.setImageResource(R.drawable.doubletick);
}else {
ivh.tick_status.setImageResource(R.drawable.singletick);
}
if(chat.Readstatus==1){
ivh.tick_status.setImageResource(R.drawable.colortick);
}
break;
case "Image":
//set Imagecmd
if(!Commonclass.isEmptyString(jsonMaking.items.get(0).ImagecmdTxt))
ivh.out_ImagecmdTxt.setText(jsonMaking.items.get(0).ImagecmdTxt);
else
ivh.out_ImagecmdTxt.setVisibility(View.GONE);
//set Image
if(!Commonclass.isEmptyString(jsonMaking.items.get(0).Base64)){
ivh.Outgoing_Image.setImageBitmap(Commonclass.decodeBase64(jsonMaking.items.get(0).Base64));
/*File file = new File(jsonMaking.items.get(0).localurl);
if(file.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ivh.Outgoing_Image.setImageBitmap(myBitmap);
}*/
}
//set Image time
ivh.outgoing_Image_Time.setText(Commonclass.GetTime(chat.dateTime));
//set tick status Image
if(chat.offlinestatus==1){
ivh.Image_tick_status.setImageResource(R.drawable.offlinestatus);
}else if(chat.Deliverystatus==1){
ivh.Image_tick_status.setImageResource(R.drawable.doubletick);
}else {
ivh.Image_tick_status.setImageResource(R.drawable.singletick);
}
if(chat.Readstatus==1){
ivh.Image_tick_status.setImageResource(R.drawable.colortick);
}
//set uploading percentage
context.runOnUiThread(new Runnable() {
#Override
public void run() {
if(chat.DownUpPercentage!=0&&chat.DownUpPercentage<90){
ivh.outgoing_circle_progress.setVisibility(View.VISIBLE);
ivh.outgoing_circle_progress.setProgress(chat.DownUpPercentage);
}else {
ivh.outgoing_circle_progress.setVisibility(View.GONE);
}
}
});
break;
}
So I'm working on a project which needs to cut up a video into multiple frames, and save them as Bitmaps on the device.
I'm using FFmpegMediaMetadataRetriever.getFrameAtTime() to obtain the individual frames, which is working, but is slow. To speed it up a bit I'm trying to implement multiple worker threads which go off and grab the frames, finally responding back to UI via an anonymous function.
I have a class MyVideoProcessor which handles the video processing, and this is called from my EditVideoActivity.
The threads start, and start processing, but shortly afterwards the EditVideoActivity dies (ANR).
From what I can see, there is nothing running on UI (apart from at the very end (which I confirm only runs once)) so not sure why the UI thread is being held up by the worker threads.
EDIT:
So I've switched out FFmpegMediaMetadataRetriever for the standard MediaMetadataRetriever and everything works. BUT I need to use FFmpegMediaMetadataRetriever, as the OPTION_CLOSEST in MMR doesn't work as it should.
EditVideoActivity:
if (mBackgroundThread==null || !mBackgroundThread.isAlive()) {
mBackgroundThread = new Thread(mMyVideoProcessor);
mBackgroundThread.start();
}
MyVideoProcessor:
public class MyVideoProcessor implements Runnable {
private static final String TAG = MyVideoProcessor.class.getSimpleName();
private MyVideo mMyVideo;
private final Context mContext;
public static final int FRAME_CUT_DURATION = 200;
private int mStartFrom = 0;
private int mCurrentDuration = 0;
private int mVideoDuration = 0;
private ArrayList<OnFrameUpdateListener> listeners = new ArrayList<>();
private ExecutorService mProcessors = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public MyVideoProcessor(Context context, MyVideo myVideo) {
mContext = context;
mMyVideo = myVideo;
}
public void setOnFrameUpdateListener(OnFrameUpdateListener listener) {
listeners.add(listener);
}
public int getCurrentDuration() {
return mCurrentDuration;
}
public void setStartFrom(int startFrom) {
mStartFrom = startFrom;
}
#Override
public void run() {
if (!mMyVideo.getProcessed()) {
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
retriever.setDataSource(mContext.getExternalFilesDir(null) + File.separator + mMyVideo.getVideo());
String time = retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
retriever.release();
mVideoDuration = Integer.parseInt(time);
int i = 0;
if (mStartFrom > 0) {
Log.d(TAG,"Attempting restore");
i = mStartFrom+1;
}
for ( i=i;i<mVideoDuration;i+=FRAME_CUT_DURATION) {
mProcessors.execute(new ExtractImageExecutor(i));
}
}
}
public class ExtractImageExecutor implements Runnable {
private int mTime;
public ExtractImageExecutor(int time) {
mTime = time;
}
#Override
public void run() {
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
retriever.setDataSource(mContext.getExternalFilesDir(null) + File.separator + mMyVideo.getVideo());
mCurrentDuration = mTime;
long startTime = System.currentTimeMillis();
Bitmap bitmap = retriever.getFrameAtTime(mTime*1000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST);
long endTime = System.currentTimeMillis();
Log.d(TAG, "Took: " + ((endTime - startTime) / 1000f));
if (bitmap != null) {
try {
int thisFrame = 0;
if (mTime>0) {
thisFrame = mTime/FRAME_CUT_DURATION;
}
//noinspection StringBufferReplaceableByString
StringBuilder frameFilename = new StringBuilder();
frameFilename.append("VIDEO_");
frameFilename.append(thisFrame).append("_");
frameFilename.append(new SimpleDateFormat("yyyyMMddHHmm", Locale.UK).format(new Date()));
frameFilename.append(".jpg");
File frameFile = new File(mContext.getExternalFilesDir(null), frameFilename.toString());
FileOutputStream fos = new FileOutputStream(frameFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
mMyVideo.addFrame(thisFrame, frameFile);
/*for (OnFrameUpdateListener listener : listeners) {
listener.onFrameUpdate(mMyVideo);
}*/
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
retriever.release();
if ((mTime+FRAME_CUT_DURATION) > mVideoDuration) {
mMyVideo.setProcessed(true);
for (OnFrameUpdateListener listener : listeners) {
listener.onFrameUpdate(mMyVideo);
}
}
}
}
}
EditVideoActivity:
public class EditVideoActivity extends Activity {
private static final String TAG = EditVideoActivity.class.getSimpleName();
private ImageView mImageView;
private MyVideo mMyVideo;
private MyVideoProcessor mMyVideoProcessor;
private Thread mBackgroundThread;
private int mCurrentDuration = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_video);
String videoFilename = getIntent().getStringExtra("videoFilename");
if (videoFilename != null) {
mMyVideo = new MyVideo(MyVideo.TYPE_EXTERIOR,"TEST",new File(videoFilename));
mMyVideoProcessor = new MyVideoProcessor(this,mMyVideo);
} else {
Log.d(TAG, "There was a problem with the video file");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.d(TAG,"Saving Instance State");
outState.putParcelable("video", mMyVideo);
outState.putInt("currentDuration", mMyVideoProcessor.getCurrentDuration());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(TAG,"Restoring Instance State");
super.onRestoreInstanceState(savedInstanceState);
mMyVideo = (MyVideo) savedInstanceState.getParcelable("video");
mCurrentDuration = savedInstanceState.getInt("currentDuration");
}
#Override
protected void onResume() {
super.onResume();
mMyVideoProcessor = new MyVideoProcessor(this,mMyVideo);
final TextView totalFrames = (TextView) findViewById(R.id.totalFrames);
mImageView = (ImageView) findViewById(R.id.imageView2);
final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.animate();
seekBar.setEnabled(false);
OnFrameUpdateListener onFrameUpdateListener = new OnFrameUpdateListener() {
#Override
public void onFrameUpdate(final MyVideo myVideo) {
if (myVideo.getProcessed()) {
File lastFrame = myVideo.getLastFrame();
totalFrames.setText(myVideo.getTotalFrames()+"");
mImageView.setImageBitmap(BitmapFactory.decodeFile(lastFrame.getAbsolutePath()));
seekBar.setEnabled(true);
progressBar.setVisibility(View.GONE);
}
}
};
mMyVideoProcessor.setOnFrameUpdateListener(onFrameUpdateListener);
if (mBackgroundThread==null || !mBackgroundThread.isAlive()) {
mBackgroundThread = new Thread(mMyVideoProcessor);
mBackgroundThread.start();
}
}
}
I use this sample to login Twitter, post status and photo. I used it for a long time. Now Twitter requires upgrading from Twitter API 1.0 to Twitter API 1.1. What do I have to do to upgrade it? I tried to replace the old lib with this lib and there is no problem so far but I'm scared of I didn't do the change completely.
You must log in via OAUTH (https://dev.twitter.com/docs/auth/using-oauth) to get connected. So you also have to register your app on dev.twitter.com.
You can find below example here https://github.com/browep/Android-OAuth-Twitter-Example.
public class Main extends Activity{
public static final String TAG = Main.class.getSimpleName();
public static final String TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT = "..."; //cannot share more then 2 lins, sorry
public static final String TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT = "...";
public static final String TWITTER_OAUTH_AUTHORIZE_ENDPOINT = "...";
private CommonsHttpOAuthProvider commonsHttpOAuthProvider;
private CommonsHttpOAuthConsumer commonsHttpOAuthConsumer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonsHttpOAuthProvider = new CommonsHttpOAuthProvider(TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT,
TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT, TWITTER_OAUTH_AUTHORIZE_ENDPOINT);
commonsHttpOAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
commonsHttpOAuthProvider.setOAuth10a(true);
TwDialog dialog = new TwDialog(this, commonsHttpOAuthProvider, commonsHttpOAuthConsumer,
dialogListener, R.drawable.android);
dialog.show();
}
private Twitter.DialogListener dialogListener = new Twitter.DialogListener() {
public void onComplete(Bundle values) {
String secretToken = values.getString("secret_token");
Log.i(TAG,"secret_token=" + secretToken);
String accessToken = values.getString("access_token");
Log.i(TAG,"access_token=" + accessToken);
new Tweeter(accessToken,secretToken).tweet(
"Tweet from sample Android OAuth app. unique code: " + System.currentTimeMillis());
}
public void onTwitterError(TwitterError e) { Log.e(TAG,"onTwitterError called for TwitterDialog",
new Exception(e)); }
public void onError(DialogError e) { Log.e(TAG,"onError called for TwitterDialog", new Exception(e)); }
public void onCancel() { Log.e(TAG,"onCancel"); }
};
public static final Pattern ID_PATTERN = Pattern.compile(".*?\"id_str\":\"(\\d*)\".*");
public static final Pattern SCREEN_NAME_PATTERN = Pattern.compile(".*?\"screen_name\":\"([^\"]*).*");
public class Tweeter {
protected CommonsHttpOAuthConsumer oAuthConsumer;
public Tweeter(String accessToken, String secretToken) {
oAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
oAuthConsumer.setTokenWithSecret(accessToken, secretToken);
}
public boolean tweet(String message) {
if (message == null && message.length() > 140) {
throw new IllegalArgumentException("message cannot be null and must be less than 140 chars");
}
// create a request that requires authentication
try {
HttpClient httpClient = new DefaultHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.appendPath("statuses").appendPath("update.json")
.appendQueryParameter("status", message);
Uri man = builder.build();
HttpPost post = new HttpPost("http://twitter.com" + man.toString());
oAuthConsumer.sign(post);
HttpResponse resp = httpClient.execute(post);
String jsonResponseStr = convertStreamToString(resp.getEntity().getContent());
Log.i(TAG,"response: " + jsonResponseStr);
String id = getFirstMatch(ID_PATTERN,jsonResponseStr);
Log.i(TAG,"id: " + id);
String screenName = getFirstMatch(SCREEN_NAME_PATTERN,jsonResponseStr);
Log.i(TAG,"screen name: " + screenName);
final String url = MessageFormat.format("https://twitter.com/#!/{0}/status/{1}",screenName,id);
Log.i(TAG,"url: " + url);
Runnable runnable = new Runnable() {
public void run() {
((TextView)Main.this.findViewById(R.id.textView)).setText("Tweeted: " + url);
}
};
Main.this.runOnUiThread(runnable);
return resp.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG,"trying to tweet: " + message, e);
return false;
}
}
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
public static String getFirstMatch(Pattern pattern, String str){
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return matcher.group(1);
}
return null;
}