Chủ Nhật, 13 tháng 10, 2013

Getting the screen density programmatically in android?

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
     case DisplayMetrics.DENSITY_LOW:
                break;
     case DisplayMetrics.DENSITY_MEDIUM:
                 break;
     case DisplayMetrics.DENSITY_HIGH:
                 break;
}
This will work in API lavel 4 or higher.

This also works:
 getResources().getDisplayMetrics().density;
This will give you:
0.75 - ldpi
1.0 - mdpi
1.5 - hdpi
2.0 - xhdpi
3.0 - xxhdpi
4.0 - xxxhdpi
enter image description here

Thứ Bảy, 5 tháng 10, 2013

Download file hoặc image trong trong android

try {
          URL url1 = new URL(name);  
              URLConnection con;
              con = url1.openConnection();
              con.setConnectTimeout(10000);
              con.connect();
               
             InputStream input = new BufferedInputStream(con.getInputStream());
       File sdCard = Environment.getExternalStorageDirectory();
       File dir = new File(sdCard.getAbsolutePath() + "/imagene/");
       dir.mkdirs();
       File file = new File(dir, i+".jpg");
       FileOutputStream f = new FileOutputStream(file);
         
         
             byte data[] = new byte[10000];
             
           //  while ((count=input.read(data))!=-1) {
           //    Log.d("phanbom","Da duoc data la:"+count);
                      input.read(data);
                   f.write(data) ;
                 
          //      }
             f.flush();
             f.close();
           
          }catch(SocketTimeoutException e){
           e.printStackTrace();
          }catch(IOException e){
          e.printStackTrace();
          }

Thứ Ba, 1 tháng 10, 2013

Get content webpage hiệu quả


31down voteaccepted
You can use HttpClient to perform an HTTP GET and retrieve the HTML response, something like this:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

Thứ Sáu, 20 tháng 9, 2013

Tương tác javascript và android native


4down voteaccepted
Yes, Android rocks at this actually.
I'm posting example code from a random example app that I made but this should get you going.
Lets start by supposing you have to global variable to your webview controlling class:
String name = "John";
String lastName = "Doe";
In the Android class controlling the webview (during onCreate() or when you setup your webview):
webView.addJavascriptInterface(new JavaScriptInterface(), "android")
Inner class to your webview controlling class:
/**
* Sets up the interface for getting access to Latitude and Longitude data
* from device
**/
private class JavaScriptInterface {
    public String getName() {
        return name;
    }
    public String getLastName() {
        return lastName;
    }
    public void onJavascriptButtonPushed(String text) {
        Toast.makeText(WebViewControllingClass.this, "The text of the pressed button is: "+text,Toast.LENGTH_SHORT).show();
    }
}
Thats it for the Android side, now to use it through Javascript:
To get the name and lastname through JavaScript:
if (window.android){
    name = window.android.getName();
    lastName = window.android.getLastName();
}
If you want to raise the toast, set a javascript whose function would be:
if (window.android){
    window.android.onJavascriptButtonPushed("Hello");
}
Edit:
I havent tried this, but a search yielded this, try it out, it should work.
If you want to use it in the other direction:
JS:
function testEcho(message){
     window.JSInterface.doEchoTest(message);
}
Android:
myWebView.loadUrl("javascript:testEcho('Hello World!')");

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