Android start activity while download video - android

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.

Related

My app is freezing after running for 20 min

I have an application which runs a stack of activities-fragment; A > a1:fragment > B > C, automatically. Activity A and its fragment is the android.hardware.camera2, which I have added to my app as a library. In order to run the stack of activities automatically I have a handler in activity A for photo capture and a handler in activity C which launches activity A:
Pass from activity A to fragment a:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_A);
if (null == savedInstanceState) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, a.newInstance()).commit();
}
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
Handler for photo capture and pass from fragment a to activity B:
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();
handler.postDelayed(new Runnable() {
#Override
public void run() {
btn.callOnClick();
}
}, 5000);
}
#Override
public void run() {
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
FileOutputStream output = null;
try {
output = new FileOutputStream(mFile);
output.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
selectedPhotoPath2 = Uri.fromFile(mFile);
Intent launchIntent = new Intent(getActivity().getBaseContext(), B.class);
launchIntent.putExtra("uriFile2", selectedPhotoPath2);
getActivity().startActivity(launchIntent);
getActivity().finish();
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Pass from activity B to activity C:
String packageName = this.getPackageName();
Intent launchIntent2 = this.getPackageManager().getLaunchIntentForPackage(packageName);
try {
launchIntent2 = new Intent(this,Class.forName("com.example.ediamanti.imageprocessing.activities.C"));
launchIntent2.putExtra("uriFile3", path);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
startActivity(launchIntent2);
finish();
Pass from activity C back to A:
final Handler handler2 = new Handler(Looper.getMainLooper());
runnable = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(C.this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
};
handler2.postDelayed(runnable, 1000);
My code is working fine but it freezes on activity A after 20 min of running. I would like to have the app running for more than an hour. When the activity freezes, no error message appears in the Logcat, while I can go back to the main menu of the application, so the activity freezes but the app is not crashing.
I have tried different approaches to solve the issue:
Use of different combination of FLAGS in activity C (CLEAR_TOP, NEW_TASK etc.) to clear the back stack history.
Remove bundles when passing intents to avoid exceeding bundle transaction limit.
Change the logger size per log buffer of the mobile device from 256KB to 16MB.
Vary handlers´waiting time.
but none of them seems to be the solution to my problem.
Does anyone have any idea of how this could be solved or any suggestion of which steps I could follow to search for the bug?Thanks!
Android monitor main thread:
enter image description here

Android Create an activity with no buttons

I am very confused as to why I cannot get this to work. I want to have a screen with no buttons run for 5 seconds while I do some things in the background, then navigate back to another screen. Is this not possible?
I have tried to put the code to run the background items in onCreate, onStart, and onResume, and all of these methods are fired before the screen actually displays. Is there another way to do this?
Edit The most recent version of my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
}
protected void onResume(){
super.onResume();
commitSync();
}
private void commitSync(){
TextView monthDayYear = (TextView)findViewById(R.id.month_day_year);
TextView hourMinuteSecond = (TextView)findViewById(R.id.hour_minute_second);
_application = (App)getApplicationContext();
try {
CountDownLatch latch = new CountDownLatch(1);
latch.await(5, TimeUnit.SECONDS);
//Ensure that we have flash
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
Camera androidCamera = Camera.open();
Camera.Parameters p = androidCamera.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
androidCamera.setParameters(p);
//Flash and then turn off
androidCamera.startPreview();
latch.await(50, TimeUnit.MILLISECONDS);
androidCamera.stopPreview();
//Flash screen white
//Get date and time
Module syncModule = _application.getModule();
syncModule.start();
Calendar syncTime = syncModule.getDateAndTime();
//http://stackoverflow.com/questions/21988004/get-time-in-hhmmss-from-seconds-in-java
monthDayYear.setText(new SimpleDateFormat("MM/dd/yyyy").format(syncTime.getTime()));
hourMinuteSecond.setText(new SimpleDateFormat("HH:mm:ss:00").format(syncTime.getTime()));
//Navigate back to MainActivity
Intent mainActivityIntent = new Intent(SyncActivity.this, MainActivity.class);
startActivityForResult(mainActivityIntent, 1);
} else {
throw new Exception("Cannot access Android Flash");
}
} catch (Exception ex) {
Util.appendLog("Exception occured in Sync: " + ex.getMessage());
}
}
Maybe this help you:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run() {
// Do some work like:
finish();
}
}, 500);
This run a code after some delay and you can put this code in your desired screen.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//The code you want to execute
}
}, timeUntilExecution);
This code should execute that run() method after the timeUntilExecution variable (in milliseconds) you could use this to execute what you want to do after the delay. Hope this helps.

Video Uploading in Android

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();
}

Update UI from running thread

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.

How to kill the thread when the new activity is started and how to override the previous thread

i have some 10 activities when the present activity is idle for 10 sec then it should go back to the main page
the code i used in each activity is
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
handler.postDelayed(this, 10000);
Intent intent = new Intent(Business_Personal.this,PrintoActivity.class);
startActivity(intent);
Thread.interrupted();
}
};
handler.postDelayed(r, 10000);
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true)
{
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
if i use this above code then till 3rd activity its working fine but in 3rd activity time is out and it's coming back to the main page
i need the code when i enter into next activity it should kill the previous thread and create a new thread
or else
override that previous thread
You need to stop the thread by using some boolean value which you set to false on the Activity's onDestroy or onPause.
while(threadNeeded){
}
public onDestroy(){
threadNeeded = false;
}

Categories

Resources