I wants to upload video file to server even after app is force stopped/closed. Right now video uploading process stops as soon as i force stop the app. Uploading is fine when app is in foreground and in background but when we stop the app by long pressing home button or by going through setting/app manager .
I have already used service and thread but it did not work.
Try this:
private void uploadData(String filePath) {
final Handler handler = new Handler();
new Thread(new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
new AsyncTask<Params, Progress, Result>() {
protected Result doInBackground(Params... params) {
//paste your uploading code here. this will work
}
}.execute(Params);
}
});
}
}).start();
}
Related
I have a server giving me live data in JSON format which updates every second. I have to display that in my android app.
I am a beginner and I tried Async Task updating every second via a thread and setting a delay on it.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// Perform the HTTP request for data and process the response.
counterAsyncTask task=new counterAsyncTask();
task.execute(REQUEST_URL);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
It runs out of memory and crashes after some time
Are there any alternates?
Try putting your code into handler thread
Runnable runnable = new Runnable() {
#Override
public void run() {
mHandler.postDelayed(this, 1000);
counterAsyncTask task=new counterAsyncTask();
task.execute(REQUEST_URL);
}
};
// start it with:
mHandler.post(runnable);
Edit: As pointed out by Mike M. and Vladyslav Matviienko and Vivek Mishra
new Runnable().run();
is not a seperate Thread. Thank you guys :)
Edit End.
When I start a new Activity that uses a separate Thread to communicate with a Server it freezes.
I start a new Activity with
Intent i = new Intent(this, AcmActivity.class);
startActivityForResult(i, acm_ui);
then I run an asynchronous call to my client class in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.acm);
//get the client implementation
ClientImpl client = ServiceManager.getService(ClientImpl.class);
client.getData(new PrivateClientCallback())
}
private class PrivateClientCallback implements GeneralCallback {
#Override
public void ok(final String response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
updateSomeView(response);
}
});
}
}
The ClientImpl.getData() looks like this:
public synchronized void getData(GeneralCallback cb) {
new Runnable() {
#Override
public void run() {
//allow networking within this Thread
//read more here: https://stackoverflow.com/questions/25093546/android-os-networkonmainthreadexception-at-android-os-strictmodeandroidblockgua
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//send some stuff to server and use the Callback
String stuff = someStuff();
cb.ok(stuff);
}.run();
}
Unfortunately my Activity freezes until the Call from the Server returned.
I would expect the Activity to start and when the server answers to update its views, unfortunately that is not what happens. I have no idea why.
new Runnable() is just a normal object. You need to create a new Thread with a runnable object. Then it'll run on a separate thread.
Check the code below
public synchronized void getData(GeneralCallback cb) {
new Thread(new Runnable() {
#Override
public void run() {
//allow networking within this Thread
//read more here: https://stackoverflow.com/questions/25093546/android-os-networkonmainthreadexception-at-android-os-strictmodeandroidblockgua
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//send some stuff to server and use the Callback
String stuff = someStuff();
cb.ok(stuff);
}).start();
}
I want to wirte an android app that will read input from user each time i press abutton and will handle it in different thread(not activity) also i dont want to open new thread each time i need an example for that.
Thanks a lot!
Get the text from user input field:
EditText editText = findViewById(R.id.yourEditTextId);
final String text = editText.getText().toString;
Then you could do something like this:
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// do something with String text
}
};
handler.post(r);
Or this:
new Thread(new Runnable() {
public void run() {
// do something with String text
}
}).start();
You can find info about threads in Android here: http://developer.android.com/guide/components/processes-and-threads.html
you could use this link here
`Thread thread = new Thread()
{
#Override
public void run() {
try {
// do something here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();`
This is my code:
protected void loadvide(final Chan channel) {
new Thread() {
public void run() {
try{
Rtmpdump dump = new Rtmpdump();
dump.parseString(channel.getUrl());
} catch (Exception e) {
}
new Thread() {
public void run() {
startActivity(new Intent(this,VideoViewDemo.class));
}
}.start();
}
}.start();
}
The function to my code is: First this part to the code:
"Rtmpdump dump = new Rtmpdump();
dump.parseString(channel.getUrl());"
begin download the video, and then the thread, start the activity "VideoViewDemo.class"
But I have a problem, because this code:
"Rtmpdump dump = new Rtmpdump();
dump.parseString(channel.getUrl());"
download the video, but never finish the download, "this is the correct function for this code".
And as never just downloaded the video, so never start the activity "VideoViewDemo.class".
I would like start activity "VideoViewDemo.class" while downloading video.
I want to write a download manager app, in the activity I add a progress bar which show the current progress to the user, now if user touch the back button and re-open the activity again this ProgressBar won't be updated.
To avoid from this problem I create a single thread with unique name for each download that keep progress runnable and check if that thread is running in onResume function, if it is then clone it to the current thread and re-run the new thread again but it won't update my UI either, Any ideas !?
#Override
public void onResume()
{
super.onResume();
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (int i = 0; i < threadArray.length; i++)
if (threadArray[i].getName().equals(APPLICATION_ID))
{
mBackground = new Thread(threadArray[i]);
mBackground.start();
downloadProgressBar.setVisibility(View.VISIBLE);
Toast.makeText(showcaseActivity.this
, "Find that thread - okay", Toast.LENGTH_LONG).show();
}
}
private void updateProgressBar()
{
Runnable runnable = new updateProgress();
mBackground = new Thread(runnable);
mBackground.setName(APPLICATION_ID);
mBackground.start();
}
private class updateProgress implements Runnable
{
public void run()
{
while (Thread.currentThread() == mBackground)
try
{
Thread.sleep(1000);
Message setMessage = new Message();
setMessage.what = mDownloadReceiver.getProgressPercentage();
mHandler.sendMessage(setMessage);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch (Exception e)
{/* Do Nothing */}
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message getMessage)
{
downloadProgressBar.setIndeterminate(false);
downloadProgressBar.setProgress(getMessage.what);
if (getMessage.what == 100)
downloadProgressBar.setVisibility(View.GONE);
}
};
Download button code:
downloadBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
downloadProgressBar.setVisibility(View.VISIBLE);
downloadProgressBar.setIndeterminate(true);
downloadProgressBar.setMax(100);
Intent intent = new Intent(showcaseActivity.this, downloadManagers.class);
intent.putExtra("url", "http://test.com/t.zip");
intent.putExtra("receiver", mDownloadReceiver);
startService(intent);
updateProgressBar();
}
});
I'd strongly recommend reading the Android Developer blog post on Painless Threading. As it states, the easiest way to update your UI from another thread is using Activity.runOnUiThread.