Thứ Năm, 25 tháng 7, 2013

So sánh Service,thread,intentservice,asynctask


ServiceThreadIntentServiceAsyncTask
When to use ?Task with no UI, but shouldn't be too long. Use threads within service for long tasks.- Long task in general.

- For tasks in parallel use Multiple threads (traditional mechanisms)
- Long task usually with no communication to main thread.
(Update)- If communication is required, can use main thread handler or broadcast intents[3]

- When callbacks are needed (Intent triggered tasks). 
- Long task having to communicate with main thread.

- For tasks in parallel use multiple instances OR Executor[1]
TriggerCall to method
onStartService()
Thread start() methodIntentCall to method execute()
Triggered From (thread)Any threadAny ThreadMain Thread (Intent is received on main thread and then worker thread is spawed)Main Thread
Runs On (thread)Main ThreadIts own threadSeparate worker threadWorker thread. However, Main thread methods may be invoked in between to publish progress.
Limitations /
Drawbacks
May block main thread- Manual thread management

- Code may become difficult to read
- Cannot run tasks in parallel.

- Multiple intents are queued on the same worker thread.
- one instance can only be executed once (hence cannot run in a loop) [2]

- Must be created and executed from the Main thread

Tương tác Service để tính tổng cơ bản (Ví dụ cơ bản)

Day la file Activity cua chung ta:
package example.bom.search;



import com.example.test.R;

import example.bom.search.ReceiveNofi.LocalBinder1;



import android.app.Activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;


import android.os.Bundle;

import android.os.IBinder;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;



public class PlayMediaActivity extends Activity implements OnClickListener{
 public boolean mBound = true;
 ReceiveNofi myService;
 TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_bom_search_playmedia);

tv = (TextView)findViewById(R.id.tv);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}


@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(mBound){
myService.unbindService(conn);
mBound = false;
}
}

   private ServiceConnection conn = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mBound = false;
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder1 local = (LocalBinder1) service;
myService = local.getReceiveNofi();
mBound = true;
}
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.button1){
if(mBound){
Intent i = new Intent(this,ReceiveNofi.class);
bindService(i,conn,Context.BIND_AUTO_CREATE );
int result = myService.sum(5,5);
tv.setText(String.valueOf(result));
}
}
}

}
 
Tiep den la giao dien:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take photo" />
    <TextView
       android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Day la text"/>

</LinearLayout>

Tiep den la Service:
 package example.bom.search;

import com.example.test.R;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class ReceiveNofi extends Service{

private final IBinder ibinder = new LocalBinder1();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return ibinder;
}

public int sum(int a,int b){
return a+b;
}


public class LocalBinder1 extends Binder{
ReceiveNofi getReceiveNofi(){
return ReceiveNofi.this;
}
}

}

Them vao AndroidManifest.xml:
<service android:name="example.bom.search.ReceiveNofi"></service>



Notification trong android 4.1

Day la activity :
package example.bom.search;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.example.test.R;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;



public class PlayMediaActivity extends Activity {
private NotificationManager notifimana;
 
   @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_bom_search_playmedia);
   Button button = (Button)findViewById(R.id.button1);
   button.setOnClickListener(new View.OnClickListener() {


@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),ReceiveNofi.class);
PendingIntent pend = PendingIntent.getActivity(getApplicationContext(), 0, intent,Intent.FLAG_ACTIVITY_CLEAR_TASK);
BufferedInputStream buf = null;

try {
buf = new BufferedInputStream(getAssets().open("button_add.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bit = BitmapFactory.decodeStream(buf);
try {
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Builder builder = new Notification.Builder(getApplicationContext());
builder.setContentTitle("Day la title");
builder.setContentText("Day la content title");
builder.setSubText("Day la sub text");
builder.setNumber(50);
builder.setTicker("Ticker");
builder.setSmallIcon(R.drawable.logo_facebook);
   builder.setLargeIcon(bit);
builder.setAutoCancel(true).setStyle(new Notification.BigPictureStyle().bigLargeIcon(bit));
builder.setDeleteIntent(pend);
builder.setPriority(0);
Notification notification = builder.build();
    notifimana = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notifimana.notify(3,notification);


}
});
}



}
 
Cac file giao dien va ReceiveNofi Activity giong nhu post truoc




Thứ Ba, 23 tháng 7, 2013

Notifcation trong android 2.3

2 file giao dien la:
File example_bom_search_playmedia.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:text="Take photo" />


</RelativeLayout>

File activity_message.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MessageActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginRight="74dp"
        android:layout_marginTop="122dp"
        android:text="Button" />

</RelativeLayout>


Cac file Activity:


package example.bom.search;

import java.io.File;

import com.example.test.R;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;



public class PlayMediaActivity extends Activity {
private NotificationManager notifimana;
 
   @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_bom_search_playmedia);
   Button button = (Button)findViewById(R.id.button1);
   button.setOnClickListener(new View.OnClickListener() {

@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),ReceiveNofi.class);
PendingIntent pend = PendingIntent.getActivity(getApplicationContext(), 0, intent,Intent.FLAG_ACTIVITY_NEW_TASK);

Notification notifi = new Notification(R.drawable.button_add,"Day la notification",SystemClock.currentThreadTimeMillis());
notifi.setLatestEventInfo(getApplicationContext(), "Day la title", "Day la text", pend);
notifimana = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//notifimana.flags |=Notification.FLAG_NO_CLEAR;

notifimana.notify(3,notifi);
}
});
}



}
 
Day la Activity se nhan:

package example.bom.search;

import com.example.test.R;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ReceiveNofi extends Activity{
   @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(3);
}
});
}
}




Thứ Hai, 22 tháng 7, 2013

Sự tương tự trong thread và asynctask

Example for using RunOnUithread:

    // some code #1
    Thread t = new Thread("Thread1") {
        @Override
        public void run() {
            // some code #2
            runOnUiThread(new Runnable() {
                public void run() {
                    // some code #3 (that needs to be ran in UI thread)

                }
            });

        }
    };
    t.start();
vs.

AsyncTask:

onPreExecute() {
   // some code #1
}

doInBackground() {
   // some code #2
}

onPostExecute() {
   // some code #3
}

Thứ Tư, 17 tháng 7, 2013

Chụp ảnh (camera) dùng intent

Giao diện nè:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:text="Take photo" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_below="@id/button1"/>
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="match_parent"
        android:layout_height="300dip"
        android:layout_alignParentBottom="true"
        android:text="ImageView"  />

</RelativeLayout>


Đây là code phần Activity:
package example.bom.search;

import java.io.File;

import com.example.test.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;




public class PlayMediaActivity extends Activity implements OnClickListener{
   private Button button;
   private Camera camera;
   private String _path;
   private ImageView imageview;
   private TextView _field;
 
   @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_bom_search_playmedia);
button = (Button)findViewById(R.id.button1);
imageview = (ImageView)findViewById(R.id.imageview);
   _field = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(this);
}



@Override
public void onClick(View v) {
_path = Environment.getExternalStorageDirectory() + "/make_machine_example.jpg";
Log.d("phanbom",_path);
    File file = new File( _path );
    Uri outputFileUri = Uri.fromFile( file );
   
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
    intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
   
    startActivityForResult( intent, 0 );
}

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode==0){
onPhotoTaken();
Log.d("phanbom","da vao day");
}
}

}

protected void onPhotoTaken()
{
 
   
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
   
    Bitmap bitmap = BitmapFactory.decodeFile( _path, options );
    imageview.setImageBitmap(bitmap);
    Log.d("phanbom","Dang trong onPhotoTaken");
    _field.setVisibility( View.GONE );
}



}
 




Thứ Ba, 16 tháng 7, 2013

Vẽ 2 hình tròn chuyển động với surfaceView

Giao diện nè :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dip"
        android:text="Exchange" />
    <SurfaceView 
        android:id="@+id/surface"
        android:layout_width="match_parent"
        android:layout_height="200dip"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"/>

</RelativeLayout>

File Activity :
 package example.bom.search;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.example.test.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Entity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

@SuppressLint("ResourceAsColor")
public class PlayMediaActivity extends Activity implements Runnable{
   private Button button;
   private SurfaceView surface;
   private SurfaceHolder holder;
   
   private boolean locker = true;
   private boolean left = true;
   Thread thread;
   private int radiuswhite,radiusblack;
   
   private int baseSpeed=1 ,speed = 0,maxRadius = 50,baseRadius = 10;
   
   @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.example_bom_search_playmedia); 
   button = (Button)findViewById(R.id.button1);
   surface = (SurfaceView)findViewById(R.id.surface);
   holder = surface.getHolder();
   thread = new Thread(this);
   thread.start();
   button.setOnClickListener(new View.OnClickListener() {
    
    @Override
    public void onClick(View arg0) {
     // TODO Auto-generated method stub
     left = !left;
    }
   });
   
  }

  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(locker){
    if(!holder.getSurface().isValid()) continue;
    Canvas canvas = holder.lockCanvas();
    draw(canvas);
    holder.unlockCanvasAndPost(canvas);    
   }
  }
  
  @SuppressLint("ResourceAsColor")
  private void draw(Canvas canvas){
   canvas.drawColor(android.R.color.transparent);
   
  // int border = 20;
  // RectF rectf = new RectF(border,border,canvas.getHeight()-border,canvas.getWidth()-border);
   Paint paint = new Paint();
  // paint.setARGB(200,135,135,135);
  // canvas.drawRect(rectf,paint);
   canvas.setViewport(200,100);
   caculateRadius();
   
   paint.setColor(getResources().getColor(android.R.color.black));
   canvas.drawCircle(canvas.getWidth()/4,canvas.getHeight()/2, radiusblack, paint);
   
   paint.setColor(getResources().getColor(android.R.color.white));
   canvas.drawCircle(canvas.getWidth()/4*3,canvas.getHeight()/2, radiuswhite, paint);
  }
  
  private void caculateRadius(){
   if(!left){
    updateSpeed(radiusblack);
    radiusblack += speed;
    radiuswhite = baseRadius;
   }else{
    updateSpeed(radiuswhite);
    radiuswhite += speed;
    radiusblack = baseRadius;
   }
   
  }
  private void updateSpeed(int radius){
   if(radius > maxRadius) speed = -baseSpeed;
   if(radius < baseRadius) speed = baseSpeed;
  }
  @Override
   protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    pause();
   }
  private void pause(){
   locker = false;
   while(true){
    try {
     thread.join();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    break;
   }
   thread = null;
  }
 
   @Override
   protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    resume();
    
   }
   
   private void resume(){
    locker = true;
    thread = new Thread(this);
    thread.start();
   }
  
}

Thứ Hai, 15 tháng 7, 2013

Ví dụ lạ trên google code về hander chưa rõ

package com.rmd.looperandhandler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {
    /** Called when the activity is first created. */
        private final String LOG_TAG = "LOOPER_AND_HANDLER";
        private Handler m_handler1, m_handler2;
        private TextView m_show_text;
        private Button m_send_message1, m_send_message2, m_send_runnable;

    private Handler.Callback m_handler_callback =new Handler.Callback() {
                
                @Override
                public boolean handleMessage(Message msg) {
                        Log.v(LOG_TAG, "m_handler_callback handleMessage fired");
                        m_show_text.setText((String)msg.obj);
                        return true;
                }
        };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        m_show_text = (TextView)findViewById(R.id.showText);
        m_send_message1 = (Button)findViewById(R.id.sendMessage1);
        m_send_message2 = (Button)findViewById(R.id.sendMessage2);
        m_send_runnable = (Button)findViewById(R.id.sendRunnable);
        
        // handler1 and handler2 both associated with main looper
        m_handler1 = new Handler()
        {
                public void handleMessage(android.os.Message msg) {
                        Log.v(LOG_TAG, "m_handler1 handleMessage fired");
                        m_show_text.setText((String)msg.obj);
                }
        }; 
        m_handler2 = new Handler(m_handler_callback);
        
        // *** 1 *** send message to handler 1
        m_send_message1.setOnClickListener(new View.OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                new Thread(){
                                        public void run() {
                                                Message msg = m_handler1.obtainMessage(1, 2, 3, "new message for handler 1");
                                                m_handler1.sendMessage(msg);
                                        } // end run()
                                }.start(); // end new Thread
                        }// end onClick
                }); // end m_send_message1.setOnClickListener

        // *** 2 *** send message to handler 2
        m_send_message2.setOnClickListener(new View.OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                new Thread(){
                                        public void run() {
                                                Message msg = m_handler2.obtainMessage(1, 2, 3, "new message for handler 2");
                                                m_handler2.sendMessage(msg);
                                        } // end run()
                                }.start(); // end new Thread()
                        } // end onClick
                }); // end m_send_message2.setOnClickListener
        
        // *** 3 *** send runnable to handler2
        m_send_runnable.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        new Thread(){
                                public void run()
                                {
                                        m_handler2.post(new Runnable() {
                                                        public void run() {
                                                                m_show_text.setText("runnable for handler 2");
                                                        } // end runnable.run
                                        }); // end m_handler2.post
                                }; // end thread.run
                        }.start();// end new Thread
                } // end onClick
        }); // end m_send_runnable.setOnClickListener
        
    }
     
}

Dùng timertask để download từ từ về

Đầu tiên là file giao diện:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show test"
        android:textSize="18sp"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"/>

</LinearLayout>

Tiếp đến là activity:

package example.bom.search;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.example.test.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Entity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class PlayMediaActivity extends Activity{
   TimerTask timetask;
   Timer t;
   ImageView imageview;
   TextView textview;
   ProgressDialog progressdialog;
   int test=0;
   private Handler threadHandler = new Handler() {
       public void handleMessage(Message msg) {
           // whenever the Thread notifies this handler we have
           // only this behavior
      if(msg.what==100){
      textview.setText("Down duoc "+msg.getData().getInt("progress")+"%");
      progressdialog.setProgress(msg.getData().getInt("progress"));
      Log.d("phanbom","Vao duoc handler:"+msg.getData().getInt("progress"));
      }else{
      dismissDialog(0);
               String imagepath = Environment.getExternalStorageDirectory().toString()+"/image.png";
               imageview.setImageDrawable(Drawable.createFromPath(imagepath));
      }
         
         
       }
   };
   @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_bom_search_playmedia);
imageview = (ImageView)findViewById(R.id.image);
textview = (TextView)findViewById(R.id.textview);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
 t = new Timer();
 t.scheduleAtFixedRate(new Mytimetask("http://marakana.com/images/generic-user.png"), 1000, 300);
}
});
}
 
  @Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
  progressdialog = new ProgressDialog(this);
  progressdialog.setTitle("Down image");
  progressdialog.setMessage("Downloading..");
  progressdialog.setIndeterminate(false);
  progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  progressdialog.setProgress(0);
  progressdialog.setMax(100);
  progressdialog.setCancelable(true);
  progressdialog.show();
  return progressdialog;

}

   

public class Mytimetask extends TimerTask{
byte data[];
int count;
    InputStream input;
    OutputStream output;
   
    int length_of_file,truoc=0,sobyte,total;
    public Mytimetask(String url1){
        showDialog(0);
                     URL url = null;
                                   try {
                                       url = new URL(url1);                    
                                       URLConnection con;
                                           con = url.openConnection();
                                       con.setConnectTimeout(10000);
                                       con.connect();
                                       length_of_file = con.getContentLength();
                                       Log.d("phanbom","Do dai file:"+length_of_file);
                                       input = new BufferedInputStream(con.getInputStream());
                                       output = new FileOutputStream("/sdcard/image.png");
                                       data = new byte[length_of_file];
                                       total = 0;
                                       sobyte = length_of_file/100;
                                   
                                     
                                   }catch(SocketTimeoutException e){
                                           e.printStackTrace();
                            }catch(IOException e){
                                   e.printStackTrace();
                            }
    }
@Override
public void run() {
// TODO Auto-generated method stub
try {
if((length_of_file-total)<sobyte) sobyte = length_of_file-total;
count=input.read(data,truoc,sobyte);
if (count!=0) {
    //count la so byte duoc doc mot lan
    // Bien total de luu so luong byte da duoc doc
    total += count;
   
    Log.d("phanbom","Luong byte chuyen va total:"+count+"|"+total+"|"+length_of_file);
    float pro = (total*100)/length_of_file;
       Message messageToThread = new Message();
                               Bundle messageData = new Bundle();
                               messageToThread.what = 100;
                              Log.d("phanbom","% la :"+total+"|"+pro);
                               messageData.putInt("progress",(int)pro);
                               messageToThread.setData(messageData);
                               threadHandler.sendMessage(messageToThread);
                             
   
   
    //sau do viet vao file tren sdcard voi du lieu trong mang data va so byte
    //moi lan viet la count
     try {
output.write(data,truoc,count) ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     truoc = total;
   
}else{
output.flush();
                                output.close();
                                Message messageToThread = new Message();
                                Bundle messageData = new Bundle();
                                messageToThread.what = 1000;
                                messageData.putString("test","OK");
                                messageToThread.setData(messageData);
                                threadHandler.sendMessage(messageToThread);
  t.cancel();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


}

Chủ Nhật, 14 tháng 7, 2013

Download image từ xa có update tiến trình và hiển thị

  1. File giao diện nè:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

       

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Download" />

        <ImageView 
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="0dip"
            android:layout_weight="1"/>

    </LinearLayout>

    Đến lượt Activity của chúng ta :

    package example.bom.search;

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.SocketTimeoutException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Locale;

    import org.apache.http.Header;
    import org.apache.http.HeaderIterator;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.ProtocolVersion;
    import org.apache.http.StatusLine;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.HttpParams;
    import org.apache.http.util.EntityUtils;

    import com.example.test.R;

    import android.app.Activity;
    import android.app.Dialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Entity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.PixelFormat;
    import android.graphics.drawable.Drawable;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnPreparedListener;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.SystemClock;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.MediaController;
    import android.widget.ProgressBar;
    import android.widget.SeekBar;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.VideoView;

    public class PlayMediaActivity extends Activity{
       ImageView imageview;
       ProgressDialog progressdialog;
       private int TIME_OUT = 20000;
       private static String url="http://marakana.com/images/generic-user.png";
       @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.example_bom_search_playmedia);
    imageview = (ImageView)findViewById(R.id.image);
    Button button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
    new ImageTask().execute(url);
    }
    });
    }
       
      @Override
    protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
      progressdialog = new ProgressDialog(this);
      progressdialog.setTitle("Down image");
      progressdialog.setMessage("Downloading..");
      progressdialog.setIndeterminate(false);
      progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      progressdialog.setProgress(0);
      progressdialog.setMax(100);
      progressdialog.setCancelable(true);
      progressdialog.show();
      return progressdialog;

    }

         
     public class ImageTask extends AsyncTask<String,String,String>{
     
      
       @Override
       protected void onPreExecute() {
        // TODO Auto-generated method stub
    //  progressdialog =  ProgressDialog.show(PlayMediaActivity.this,"","Uploading video");
        super.onPreExecute();
        showDialog(0);
       }
    @Override
    protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
     int count;
     URL url = null;
    try {
    url = new URL(params[0]);
       URLConnection con;
    con = url.openConnection();
       con.setConnectTimeout(TIME_OUT);
       con.connect();
      int length_of_file = con.getContentLength();
      InputStream input = new BufferedInputStream(con.getInputStream());
      OutputStream output = new FileOutputStream("/sdcard/image.png");
      byte data[] = new byte[1024];
      long total = 0;
      while ((count=input.read(data))!=-1) {
    //count la so byte duoc doc mot lan
    // Bien total de luu so luong byte da duoc doc   
    total += count;
    Thread.sleep(1000);
    publishProgress(""+total/length_of_file*100);
    //sau do viet vao file tren sdcard voi du lieu trong mang data va so byte
    //moi lan viet la count
                             output.write(data,0,count) ;
          }
      output.flush();
      output.close();
      
    }catch(SocketTimeoutException e){
    e.printStackTrace();
    }catch(IOException e){
    e.printStackTrace(); 
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

    return null;
     
    }
    @Override
    protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    dismissDialog(0);
    String imagepath = Environment.getExternalStorageDirectory().toString()+"/image.png";
    imageview.setImageDrawable(Drawable.createFromPath(imagepath));

    }
    @Override
    protected void onProgressUpdate(String... values) {
    // TODO Auto-generated method stub
    progressdialog.setProgress(Integer.parseInt(values[0]));
    progressdialog.setMessage(values[0]+"%");

    }
      
    }
       
    }