Don't know if it is safe to implement Asynctask like that - android

I made a code on android and i would like to receive some opinions from stackoverflow people.
It is about a code which i used the AsyncTask class... But i don't know if it is coded good or not ...
Here it is the code:
package com.example.basicmaponline;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.mlab.android.basicoverlays.PostgreSQL;
import com.mlab.android.basicoverlays.SQLloja;
public class Intro extends Activity{
//SQLlistLoja listaLoja;
HashMap<String, SQLloja> listaLoja;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
//Intent openMainActivity = new Intent("com.example.basicmaponline.MAINACTIVITY"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
//startActivity(openMainActivity);
try {
listaLoja = new loadDatabase().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(listaLoja !=null){
for(SQLloja loja : listaLoja.values()){
Log.d("ASYNC25", loja.getNome() );
}
}
else{
Log.d("ASYNC25", "NAO GUARDOU!" );
}
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
Intent openMenu = new Intent("com.example.basicmaponline.MENU"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
openMenu.putExtra("listaLoja",listaLoja);
startActivity(openMenu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//ourSong.release(); //release the music and we are done with you
finish();
}
//#SuppressWarnings("rawtypes")
public class loadDatabase extends AsyncTask<Void, Void, HashMap<String,SQLloja>>{
#Override
protected HashMap<String,SQLloja> doInBackground(Void... params) {
// TODO Auto-generated method stub
HashMap<String,SQLloja>listaLojas = new HashMap<String, SQLloja>();
try{
PostgreSQL pSQL = new PostgreSQL(host,db, username, password);
String sql = pSQL.getLojasCidadao();
Statement st = pSQL.getConnection().createStatement();
ResultSet rs = st.executeQuery(sql);
Log.d("ASYNC2","Entrei na thread ASYNCTASK");
while(rs.next()){
int lcId = Integer.parseInt(rs.getString(1));
String lcNome=rs.getString(2);
String lcCP = rs.getString(3);
int lcDistrito = Integer.parseInt(rs.getString(4));
int lcConselho = Integer.parseInt(rs.getString(5));
double lcAltitude = Double.parseDouble(rs.getString(6));
double lcLongitude = Double.parseDouble(rs.getString(7));
String lcTelefone = rs.getString(8);
boolean lcEstado = Boolean.parseBoolean(rs.getString(9));
String lcRua = rs.getString(10);
SQLloja loja = new SQLloja(lcId,lcNome,lcCP,lcDistrito,lcConselho,lcAltitude,lcLongitude,lcTelefone,lcEstado,lcRua);
listaLojas.put(loja.getNome(),loja.clone());
String informacoesLoja = "Rua : "+lcRua+"\nC.P. : "+lcCP+"\nTel. : "+lcTelefone;
Log.d("ASYNC",lcNome+" Altitude = "+lcAltitude+" Longitude = "+lcLongitude+" Rua = "+lcRua);
}
//listaLoja = new SQLlistLoja(listaLojas);
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if(listaLojas!=null){
Log.d("ASYNC","entrei no if da listaLojas");
for(SQLloja loja : listaLojas.values()){
Log.d("ASYNC", loja.getNome() );
}
}
else Log.d("ASYNC","listaLoja nula ! PQP !");
return listaLojas;
}
#Override
protected void onPostExecute(HashMap<String,SQLloja> listaLojas){
listaLoja = listaLojas;
for(SQLloja loja : listaLoja.values()){
Log.d("ASYNC24", loja.getNome() );
}
}
}
}
I'm not sure but, i think that the return value from AsyncTask isn't made by the right way although its working on my android application.
Some opinions will be welcomed.
Thank you ! :)

When you use the AsyncTask its good create a class instance to implement the methods, and then when you want to use, create a variable asynctask with the method .start(); if i'm no mistaken.
And its good too create a ProgressDialog.

Related

My activity changes orientation on screen lock

I have set orientation of my activity to landscape and it remains in that state except one case.and the case is screen lock .when my activity is running and i lock my screen it changes orientation from landscape to portrait for little bit of time and causes my app to restart and which I don't want.any solution...?
package com.example.hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity{
VideoView vv;
public ArrayList<String> list = new ArrayList<String>();
int n,positio = 0;
String file = null;
Spinner spin;
MediaPlayer mp;
Intent intent;
File fl;
boolean isPlaying = true;
boolean screenOn = false;
PowerManager pm;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Log.d("zaid iqbal", "in onCreate");
requestFullScreen();
setContentView(R.layout.activity_main);
vv = (VideoView)findViewById(R.id.video);
spin = (Spinner)findViewById(R.id.spinner);
MediaController mc = new MediaController(this);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
vv.setMediaController(mc);
setupSpin();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onPause");
isPlaying = vv.isPlaying();
screenOn = pm.isScreenOn();
if (screenOn && isPlaying) {
// Screen is still on, so do your thing here
n++;
positio = vv.getCurrentPosition();
vv.pause();
//Toast.makeText(this, file, Toast.LENGTH_LONG).show();
intent = new Intent(this,playBack.class);
intent.putExtra("file", file);
intent.putExtra("position", positio);
intent.putExtra("n", n);
startService(intent);
}
if(!isPlaying){
positio = vv.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onResume");
if(!isPlaying){
vv.setVideoPath(file);
vv.seekTo(positio);
}else{
async aa = new async();
aa.execute();
}
super.onResume();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
public void requestFullScreen(){
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void setupSpin(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/");
listFiles(root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//Log.d("zaid iqbal","in onclick of spin");
if(n == 0){
file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/" + list.get(position);
Log.d("zaid", file);
//Toast.makeText(MainActivity.this, "original" + file, Toast.LENGTH_SHORT).show();
vv.setVideoPath(file);
vv.start();
}
//n = 0;
/*File fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
position = Integer.parseInt(reader.readLine());
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file);
writer.write(position);
writer.write(n);
position = Integer.parseInt(reader.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void listFiles(File f){
try{
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String filenameArray[] = file.toString().split("\\.");
String extension = filenameArray[filenameArray.length-1];
//if(extension == "mp4" || extension == "3gp")
list.add(file.getName());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
class async extends AsyncTask<String,Long,Long>{
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
if(intent != null){
stopService(intent);
//Reading file
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
//Log.d("zaid iqbal", "getted file");
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
//Toast.makeText(MainActivity.this, "getted file" + file, Toast.LENGTH_SHORT).show();
positio = Integer.parseInt(reader.readLine());
n = Integer.parseInt(reader.readLine());
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n != 0){
n=0;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file + "\n" + positio + "\n" + n);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vv.setVideoPath(file);
vv.seekTo(positio);
vv.start();
}
super.onPostExecute(result);
}
}
}
First, I would read up on Android activity lifecycle. Personally I think this is the way begin to address the issue -
http://developer.android.com/training/basics/activity-lifecycle/index.html
Another option to investigate -
android:configChanges="orientation|keyboardHidden|screenSize"
how to stop activity recreation on screen orientation?
Try this in your Activity Tag of Manifest file :
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Here Orientation refers to Configuration changes which you want to handle by your own.
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle.
Use onSaveInstanceState() and onRestoreInstanceState() if you want to restore your previous state of an activity.
Refer this also
You may try to call setRequestedOrientation() in you activity so the orientation is forced.

connect via socket with a button

are days that I'm stuck with this problem. I created an application with the fragment and tabs, I have to insert a button that when clicked connects to a certain ip and to a certain port, I have no idea how to write and how to put it, they are only able to connect when it starts mainActivity, but I wish it were possible to control it by a button, can you help?
First, with last versions of Android framework all network operations can't be performed from the main thread (ie the thread that manage the UI). So, you need to use your own thread to make the connection.
An example:
package it.resis.solarapp.activities.fourcloud.application;
import it.resis.solarapp.R;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class CopyOfActivity4CloudConfiguration extends Activity {
private volatile Socket socket = null;
private boolean connectionOk = false;
private Button buttonDisconnect;
private Button buttonConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
buttonConnect = findViewById(R.id.buttonConnect);
buttonConnect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
InetSocketAddress addr = new InetSocketAddress("192.168.1.1", 80);
new ConnectToIpTask().execute(addr);
}
});
buttonDisconnect = findViewById(R.id.buttonDisconnect);
buttonConnect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
new CloseSocket().execute();
}
});
buttonDisconnect.setEnabled(false);
buttonConnect.setEnabled(true);
}
private class ConnectToIpTask extends AsyncTask<InetSocketAddress, Void, Boolean> {
#Override
protected Boolean doInBackground(InetSocketAddress... params) {
InetSocketAddress addr = params[0];
try {
socket = new Socket(addr.getAddress().toString(), addr.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
connectionOk = result;
// update here the ui with result
if (result) {
buttonDisconnect.setEnabled(true);
buttonConnect.setEnabled(false);
}
}
}
private class CloseSocket extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
socket.close();
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
buttonDisconnect.setEnabled(false);
buttonConnect.setEnabled(true);
}
}
}
I could, I changed the line of code
from:
#Override
protected Boolean doInBackground(InetSocketAddress... params) {
InetSocketAddress addr = params[0];
try {
**socket = new Socket(addr.getAddress().toString(), addr.getPort());**
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
to
#Override
protected Boolean doInBackground(InetSocketAddress... params) {
InetSocketAddress addr = params[0];
try {
**socket = new Socket("192.168.1.1", 80);**
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
thanks to all

Printing integer values in a textview and thread sleep time

How do I print integer values in a textview and also when I increasing the sleep time in the thread its not working correctly in android.
package com.example.chaljayar;
import java.util.concurrent.Delayed;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable
{
TextView Tv;
int num = 0, i = 0;
String con = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tv = (TextView)findViewById(R.id.Text);
Thread test = new Thread(this);
test.start();
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(i <= 100)
{
try{
con += Integer.toString(i);
Tv.setText(con);
Thread.sleep(1000);
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
i++;
}
}
}
Try this To Thread alone and the other out of (try/catch) :
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
If you want any thing about print int values in textview show this link please :
Integer value in TextView

onProgressUpdate() not called during downloading file from dropbox

I have been stucking from last 2 days.. In my case the onProgressUpdate() is not called.. So it is not updating the progress bar.. can any one please have a look and suggest.. Thanks. here is my code
package com.example.downloadupload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private final ProgressDialog uDialog;
private long dFileLen;
long bytess;
public DownloadFile(Context context,
DropboxAPI<AndroidAuthSession> mDBApi) {
dDBApi=mDBApi;
dContext=context.getApplicationContext();
uDialog = new ProgressDialog(context);
uDialog.setMax(100);
uDialog.setMessage("Downloading Image");
uDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
uDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String path1= Environment.getExternalStorageDirectory()+"/log.txt";
BufferedOutputStream out=null;
try {
File file = new File(path1);
out = new BufferedOutputStream(new FileOutputStream(file));
dDBApi.getFile("/log.txt", null,out,new ProgressListener() {
/* #Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}*/
#Override
public void onProgress(long bytes, long total) {
// TODO Auto-generated method stub
bytess=bytes;
publishProgress(bytes);
}
});
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while downloading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {}
}
}
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(progress);
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
uDialog.setProgress(percent);
System.out.println("Hi progressing");
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
uDialog.dismiss();
System.out.println("calling post execute");
}
}
Instead of this
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
Use this
int percent = (int)(100.0*(double)progress[0]/TotalsizeOfFile + 0.5);
And you can uncomment
#Override
public long progressInterval()
{
// Update the progress bar every half-second or so
return 500;
}
It's working for me.
I think the mistake is this
bytess=bytes;
publishProgress(bytes);
and then,
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
here, progress[0] = bytess -> everytime, hence progress might not be getting updated.
Make onProgress() something like this
public void onProgress(long bytes, long total) {
// TODO Auto-generated method stub
long[2] bytess = {bytes, total};
publishProgress(bytess);
}
and calculate percentage
int percent = (int)(100.0*(double)progress[0]/progress[1]+ 0.5);

Why is this app running slow?

Why does this app stop answering then I press play? It sometimes show a "the application is not responding" but it works if I wait.
It works nice on my emulator, but not on my phone (or any other phone I tried).
All it does is streaming sound.
package comunicera.se;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Godnattsaga extends ListActivity {
/** Called when the activity is first created. */
ListView list;
TextView spelandesSagqa;
//private ProgressDialog mProgressDialog;
ProgressBar myProgressBar;
int myProgress = 0;
MediaPlayer mp = new MediaPlayer();
String BASEURL = "http://godnattsaga.nu/sagor";
public static long glCurrentSaga = 0;
public static String giCode = null;
int giAntalSagor = 0;
int possWhenPaused = 0;
ProgressBar myBufferProgressBar;
TextView buffrarText;
int progress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
new Thread(buffer).start();
String lsSagor = getFileFromUrl(BASEURL+"/gratisSagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
//String saga = laList[0].replaceAll("#", "\n");
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
changeSpelandesSaga(laSaga[0]);
setList (guiLaList);
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String liCode = kop(id);
glCurrentSaga = id;
String[] laSaga = laList[(int) glCurrentSaga].split("#");
changeSpelandesSaga(laSaga[0]);
}
});
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay(laList);
}
});
glCurrentSaga = 0;
changeSpelandesSaga(laSaga[0]);
}
catch (Exception e)
{
changeSpelandesSaga("Check your connection, are you in flightmode?");
}
}
public void selectDownloadOrPLay(String[] laList) {
String[] laSaga = laList[(int) glCurrentSaga].split("#");
String url = BASEURL+"/gratis/"+laSaga[0].replaceAll(" ", "_")+".mp3";
if (mp.isPlaying())
{
mp.pause();
possWhenPaused=mp.getCurrentPosition();
}
else if (possWhenPaused != 0)
{
mp.start();
}
else
{
startSaga (url);
}
}
private String kop(long id)
{
mp.pause();
return "gratis";
}
public void setList (String[] laList)
{
/*
*
final String[] lAList = new String[3];
lAList[0] = "Saga 1 \n";
lAList[1] = "Saga 2 \n";
lAList[2] = "Saga 3";
setList (lAList);
*
*/
setContentView(R.layout.main);
ArrayAdapter<String> appointmentList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, laList);
list=(ListView)findViewById(android.R.id.list);
list.setAdapter(appointmentList);
}
public void changeSpelandesSaga(String sagaRubrik)
{
possWhenPaused = 0;
TextView t = new TextView(this);
t=(TextView)findViewById(R.id.spelandesSaga);
t.setText(Html.fromHtml("<b>"+sagaRubrik+"</b>"));
}
private void startSaga(String url)
{
try {
mp.reset();
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
myProgressBar=(ProgressBar)findViewById(R.id.mProgressDialog);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
double poss = 0.0;
double sagaleng = 0.0;
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
poss = mp.getCurrentPosition();
sagaleng = mp.getDuration();
progress = (int) ((int)poss / sagaleng * 100);
myProgress = progress;
myProgressBar.setProgress(progress);
}
};
};
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
showNoConnection ();
return null;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
return connected;
}
private static void showNoConnection()
{
}
private Runnable buffer = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t)
{
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//SpelaPause.setImageURI("pauseicon");
myBufferProgressBar = (ProgressBar)findViewById(R.id.mBuffrar);
TextView bufferText = (TextView)findViewById(R.id.buffrarText);
if (mp.isPlaying() && progress == 0)
{
myBufferProgressBar.setVisibility(View.VISIBLE);
bufferText.setVisibility(View.VISIBLE);
}
else
{
myBufferProgressBar.setVisibility(View.INVISIBLE);
bufferText.setVisibility(View.INVISIBLE);
}
}
};
};
}
If your application uses internet, it is possible, that the phone has worse connection than your comp. For example, if they both run on the SAME WiFi, at the same point, phones are connected MUCH worse than PC. Slower connection - you have to wait...
Read http://developer.android.com/guide/practices/design/responsiveness.html and http://developer.android.com/guide/practices/design/performance.html - VERY useful. For example, you will know the name of your problem - bad responsiveness (not performance) - for better further searches. :-)
All long-lasting tasks should be run in separate thread, not in UI thread. You call getFileFromUrl(..) from onCreate(..) method. This cause hangings.
I recommend you not to do any time consuming task in onCreate(..) method. In general an activity won't be shown till onCreate(..) is finished.
You are using getFileFromUrl in your onCreate method. Your method just performs the download action, which in case could last some time. You should always move long running tasks into it's own thread and notify the UI thread only.
Consider never running big logic in the UI thread, the UI thread should only be responsible for UI stuff.
To download a file in an async manner try to use the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html
This code works, without responsiveness problems. But the buffering takes to long time so I need another solution.
I'm posting some code if someone else have the same problem
package comunicera.se;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GodnattsagaTest1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay();
}
});
}
public void selectDownloadOrPLay() {
Toast.makeText(getApplicationContext(), "Before ... ", Toast.LENGTH_SHORT).show();
Saga.startSaga ();
Toast.makeText(getApplicationContext(), "after ... ", Toast.LENGTH_SHORT).show();
}
}
class Saga
{
static MediaPlayer mp = new MediaPlayer();
static void startSaga()
{
new Thread(spelaSaga).start();
}
private static Runnable spelaSaga = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource("http://godnattsaga.nu/sagor/gratis/Fisken.mp3");
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
};
}
I believe it has something to do with the progress bar you use. I use one and it slows my app. Not sure if the progress bar must slow the app or there is another way to avoid this though.

Categories

Resources