Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Sunday, September 11, 2011

Android Programming - Send SMS

Android is for mobile, so it must preserve support to mobile function like calling and SMS.
In Android SMS can be done by starting SMS activity class via Intent or create yourself a SMS Sending class.
I'll create my own method to send SMS.
private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:                    
                        Toast.makeText(getBaseContext(), SENT, 
                                Toast.LENGTH_SHORT).show();

                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, null);        
    }
You need to argument to start this function, sms number and sms message. Just fill it and you're done. It check too for error that may found.
You can check SMS using Emulator, create 2 emulator and you can send a sms from one to another emulator using the emulator number, for example 5554 or 5556.

Categories: , , , ,

Android Programming - Override Back Button

Overriding back button is much more simple than options menu before.

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("You've pressed the back button\nThanks.")
               .setTitle("Back Pressed")
               .setCancelable(true);
        builder.create().show();
    }

That's it. You're done. It create an AlertDialog when back button pressed.

Categories: , , , , ,

Android Programming - Override Options Menu

To override options menu simply add this code to your activity.

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.listmenu, menu);
        return true;
    }



@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case R.id.about:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Overriding Options Menu\n(c) 2011")
                   .setTitle("Menu Pressed")
                   .setCancelable(true);
            builder.create().show();
            return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }

The first section is the overriding of menu button, whenever menu button pressed, it will call you menu from listmenu.xml that placed in the folder res/menu.
Then the second section is the function that run when user click your options menu. For this code, I will create an AlertDialog that shows some text with close button in it.
Don't forget to create your listmenu.xml. Here is the example.
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/about" android:title="About"></item>
</menu>

Categories: , , , , ,

Android Programming - Url Connect

This the basis for web service. Android + Web Service is a future will be for me. With open platform you can access open information. That's really great I think.
Simple, with a piece of code to access web service in Android, but remember, this is basic implementation, you need add more functionality for sure, like checking internet connection, handling the error and encoding the output (XML or JSON).
This is my code, simple, as a function that you can called anywhere in your program.
public String connect(String url) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
             sb.append(line);
        }
        return sb.toString();
    }

You need an input with type string that contained the url of the web services, the code then connect and copy the output as a string too.
For more advanced usage you can directly encoded the output string to format that you need. :)

Categories: , , , , , ,

Saturday, September 10, 2011

Android Programming - Setting Up Your Environment

This is my first article of Android Programming Series in my blog. I'll share you how to set up an environment to begin programming in Android. Actually it was easy and the Android Developer site have a full article about this too, but maybe you'll want to read mine, I'll include with several troubleshooting I've found when I first time trying to install this SDK.

Android application made using the Android SDK (Standard Development Kit) and it could use also the NDK (Native Development Kit) that allows you to use a language other than Java (C or C + +), of course it usage for advance programming that really need the efficiency and effectiveness of specific code (socket programming, 3D, high-scale data management).

We can use the interface of Eclipse Java version as an IDE (Integrated Development Environment) with the ADT plugin. Actually, we can also use other Java-based IDE like IntelliJ and NetBeans, but I think most easily with Eclipse because ADT has been good enough in doing the integration, on the other IDE you will still need to generate Eclipse project files as a base in the IDE and then do the programming in another IDE after importing. There also needs  Java Runtime Environment and Java Development Kit to be able to run the program.

Eclipse is a multiplatform IDE, you can use a variety of Linux operating system (Ubuntu recommended), Windows (XP, Vista, 7) and MacOSX from version 10.5.8 (x86).

So before it can begin to make the Android program we should prepare: Eclipse, ADT, Android SDK, JRE, JDK and at least one Android platform to make Android Virtual Devices later.

1. Installing JDK and JRE

Please go to the Java download site. Download the JDK and JRE is the latest if it does not exist on your computer. Please adjust your computer operating system. For Linux it can be downloaded from the repository using your favorite repository management software, there is also an open version JDK.



Note : I bet you found no error in this step, Java installation (both JRE and JDK) is simple (just click the installer) and realy straight forward.

2. Installing Android SDK

Downloaded from the Android Developer site http://developer.android.com. There are also provided the installation guide. For Windows as usual just click on the installer and specify the location where we want to put the Android SDK installation folder, please notice the location of this folder, because it will be used for setting the Eclipse as well. In Linux and Mac I think you can do that in simple command too. I use Ubuntu, so I download the .deb version installer, and it works fine, just click, input the administrator password and installed. I placed the SDK in my home folder (Ubuntu) and C:\Program Files in Windows.




Note : it is easy too, just remember the place of Android SDK folder as a mention before, it's a must.

3. Installing Eclipse

Eclipse can be downloaded from its website http://www.eclipse.org . Eclipse does not need to install, just extract your downloaded achive and Eclipse can be used by running eclipse.exe in it. You will be asked about the workspace, select the location where you want to put your Eclipse workspace, in this folder all Eclipse project files will reside. Check the checkbox at the bottom so that you are not continually asked about the workspace when running Eclipse.





Note : Maybe you'll find some error in this step, check that your Eclipse Download is Java IDE version, because Eclipse has separate and various IDE for other language. Check your OS version, remember that maybe your hardware support 64bit OS (you have AMD 64 sticker :p) but ussualy your OS is not 64 bit edition, so you need to download the 32bit version (for SDK and Eclipse). Eclipse will check for JRE installation too, and maybe other dependency, just fill out other dependency to stop the error.

4. Installing ADT

It will be done through Eclipse, open Eclipse, then to Help >> Install New Software >> Add. Enter Name: ADT, location: https://dl-ssl.google.com/android/eclipse . Then click OK. This can be done when your computer is connected directly to the Internet, otherwise you can download the installation file first Android Developer ADT from the site and then install it from Eclipse by selecting the type Archive in the Add dialog box earlier and go to your ADT installation files.

 After this you must connecting your SDK with Eclipse preferences. Go to Window >> Preferences >> Android and add your SDK folder location.




Note : still remember the SDK folder places?Good. Maybe some error will found in this step, try checking internet connection or redownloading the archive.

5. Installing the Android Platform

After successfully installing the ADT you even have the Android SDK and AVD menu in the Window Manager. Also, you can already see there are options to make the Android project in the File >> New >> Other. But you can not make it, because it does not have the build target and AVD (Android Virtual Machine).

Android Platform installation is done from Window >> Android SDK and AVD Manager. It can also be accessed directly from the Android SDK installation file. Go to the Available Packages, and select at least one Android platform. It also can only be done if you are directly connected to the Internet.

If not, there is a little trick to be able to install it offline Android Platform, SDK is another component of the platform can be retrieved from the xml file link http://dl-ssl.google.com/android/repository/repository.xml . It can be seen in the file name such as android-2.2 and can be downloaded from the address http://dl-ssl.google.com/android/repository/ . To install, copy the files downloaded into a new folder called / temp inside the Android SDK installation folder. Then run the AVD, select the appropriate packages that were downloaded earlier and finish. Emulator can be made. Can also be installed in a way more easy to extract the contents of the zip file directly into a folder earlier platforms. Then you can check on the Installed Package AVD Manager, your platform is already installed there.


 Note : problem that can be found is still about the internet connection, for slow connection I recommended the offline install way.

6. Creating AVD

AVD is made ​​from the Window menu >> the Android SDK and AVD Manager >> Virtual Devices >> New. Specify the name of AVD (preferably containing the version, easy to remember), the build target (I think at least 2.1 or 2.2 for now), size SD Card if you want to use, check to be enabled Snapshot, skins use the built-in first, the hardware does not need to be changed first, and can directly click Create AVD.


 Note : Just fill as it must be, minimal error I think, because ADT and Eclipse is pretty good to check our input.

Yeahh...You have done, you have a setting up development environment to start programming in Android. :)

Categories: , , , , , , , , ,

Apakah Android Itu?


Menurut Google IO 2010 :
  • Opensource dan openplatform untuk pengembangan teknologi mobile
  • SDK, API dan sourcecodenya tersedia untuk diunduh
  • Tidak ada lisensi
  • Bisa merubah bagian system semau kita
Android menjanjikan keterbukaan dan kebebasan ini. Berbasis dari kernel Linux (Pak Linus Torvalds anda luar biasa sekali!!) yang dimodifikasi untuk mengakuisisi teknologi mobile yang memorinya relative kecil. Setiap aplikasi dijalankan melalui suatu Virtual Machine bernama Dalvik (dari nama daerah asal leluhur Programmernya, Pak Bornstein). Dalvik VM ini menerjemahkan set instruksi dari kode program agar bisa dilakukan/dijalankan oleh mesin. Dalvik tidak sama dengan JavaVM (JRE), perbedaan utamanya adalah JavaVM merupakan stack-based VM (pengalamatan memorinya system stacking) sementara Dalvik merupakan register-based, menggunakan register yang memang lebih hemat memori dalam pengoperasiannya, eksekusinya lebih cepat, tapi membuat file compilasi program yang lebih besar. DalvikVM merupakan interpreter-only VM yang menjalankan file executable *.dex, format yang dioptimasi untuk ukuran yang efisien dan memory-mappable execution. Dapat menjalankan Java Class yang yang ditransformasi menjadi format nativenya dengan dx tool yang sudah tersedia di SDK. Menggunakan Kernel Linux 2.6, Dalvik yang berjalan diatas Kernel itu dioptimasi untuk fasilitas threaded programming, fungsi jaringan dan manajemen memory level bawahnya dari sini(hubungan dengan hardware termasuk juga driver). 
Android merupakan sistem operasi Linux Multiuser, dimana setiap aplikasi Android menjadi user tersendiri, dengan user id tertentu yang digunakan oleh sistem, dengan pengesetan permissions khusus bagi user (baca: aplikasi) untuk setiap filenya. Setiap proses punya VMnya masing-masing, sehingga setiap aplikasi berjalan dalam isolasi. Ini merupakan cara pengamanan yang dilakukan Android, sehingga setiap aplikasi hanya memiliki hak terhadap resourcenya masing-masing. Meskipun tetap ada cara untuk mengakses file milik aplikasi lain atau bahkan sistem resource, dengan pemberian permissions tertentu dan harus disetujui user saat instalasi.
Komponen Aplikasi Android :
  • Activities : satu screen dengan user interface (UI).
  • Services : component yang berjalan di background, tidak memiliki UI.
  • Content providers : memanage data aplikasi/storage, bisa melalui SQLite, web dan persistent storage.
  • Broadcast receivers : komponen yang merespon system broadcast messages.
Aktivasi Komponen :
  • Activities : menggunakan Intent untuk startActivity() atau startActivityForResult().
  • Services : menggunakan Intent untuk startService() atau bindService().
  • Broadcast receivers: menggunakan Intent untuk sendBroadcast(), sendOrderedBroadcast() atau sendStickyBroadcast().
  • Content provider : memanggil query() pada ContentResolver.

Categories: , , , , , , , ,

Thursday, July 21, 2011

Belajar Java ep4 Operator

Operator terdiri dari operator logika dan aritmatika. Untuk yang aritmatika saya kira mudah dipahami, seperti biasa kita gunakan di dunia nyata kok.

Operator Aritmatika
Arti
Operator Relasi
Arti
Operator Logika
Arti
+
Penambahan
==
Sama dengan
&
AND
-
Pengurangan
!=
Tidak sama dengan
|
OR
*
Perkalian
> 
Lebih dari
^
XOR
/
Pembagian
< 
Kurang dari
||
Short-circuit OR
%
Modulus(sisa pembagian)
>=
Lebih dari sama dengan
&&
Short-circuit AND
++/--
Increment dan decrement (+/- 1)
<=
Kurang dari sama dengan
!
NOT
Cara mudah untuk memahami operasi operator logika adalah dengan program seperti ini :
public class OperatorLogika {

      public static void main(String[] args) {
            boolean P;
            boolean Q;
           
            P = true; Q = true;
            System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
            System.out.println((P) + "\t" + (Q) + "\t" + (P&Q) + "\t" + (P|Q) + "\t" + (P^Q) + "\t" + (!P));
            P = true; Q = false;
            System.out.println((P) + "\t" + (Q) + "\t" + (P&Q) + "\t" + (P|Q) + "\t" + (P^Q) + "\t" + (!P));
            P = false; Q = true;
            System.out.println((P) + "\t" + (Q) + "\t" + (P&Q) + "\t" + (P|Q) + "\t" + (P^Q) + "\t" + (!P));
            P = false; Q = false;
            System.out.println((P) + "\t" + (Q) + "\t" + (P&Q) + "\t" + (P|Q) + "\t" + (P^Q) + "\t" + (!P));

      }

}
Output yang didapat seharusnya :

Categories: , , , , , , , , , ,

Belajar Java ep3 Data Types dan Variabel

Data Types

Tipe
Arti
Boolean
Nilai true/false
byte
Integer 8-bit (-128 – 127)
char
Karakter
double
Double-precision floating point
Float
Single-precision floating point
Int
Integer (-2147483648 – 2147483647)
Long
Long Integer (-9223372036854775808 – 9223372036854775807)
Short
Short Integer (-32768 -- 32767

Ketikkan kode ini di Class baru dengan nama DataType :
public class DataType {
      public static void main(String[] args) {
            int bil1 = 1123;
            long bil2 = 233456573;
            short bil3 = 25777;
            char ch = 'C';
            double fl1 = 10.6;
            boolean boo = true;
           
            System.out.println("bil1 contains : " + bil1);
            System.out.println("bil2 contains : " + bil2);
            System.out.println("bil3 contains : " + bil3);
            System.out.println("ch contains : " + ch);
            System.out.println("fl1 contains : " + fl1);
            if(boo) System.out.println("boo contains : " + boo);
      }
}

Output yang diperoleh akan seperti ini :


                      

Variabel

Deklarasi  variabel dilakukan dengan sintaks : tipe nama-variabel. Juga dapat langsung dilakukan inisialisasi nilai variabel dengan penambahan =.  Dapat juga nilainya di-inisialisasikan dengan dinamis melalui hasil operasi variabel lain bahkan pemanggilan Method.
public class Variabel {

      /**
       * Percobaan inisialisasi variabel
       */
      public static void main(String[] args) {
            int bil4;
            int bil5 = 43; //inisialisasi langsung
            bil4 = 2;
            System.out.println(bil4 + " dan " + bil5);
            int bil6 = bil4 * bil5; //inisialisasi dinamis
            System.out.println("Nilai dari bil6: " + bil6);
           
            /*
             *    Hasil running program :
             *    2 dan 43
             *    Nilai dari bil6: 86
             */
      }

}

Categories: , , , , , , , , , ,

Copyright © Johannes Dwi Cahyo | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com | BTheme.net      Up ↑