Pages Navigation Menu

Coding is much easier than you think

how to send sms in android application

Posted by in Android

The android.telephony package contains the SmsManager and SmsMessage classes. The SmsManager defines many important SMS-related constants, and also provides the sendDataMessage, sendMultipartTextMessage, and sendTextMessage methods. As long as your app is configured with proper permissions to send text messages (using the android.permission.SEND_SMS permission) you can send text messages to whoever you like SmsManager to send SMS messages
 
** UPDATE: Android Complete tutorial now available here.
 
Example:1

sendTextMessage (
String phoneNumber,
String serviceCenterAddress,
String text,
PendingIntent sentIntent,
PendingIntent deliveryIntent
)

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("9884788301", null, "hi simplecodestuffs!", sentPI, deliveredPI);

Sent Intent is a pending intent which will be triggered when sms is sent from your phone and delivery Intent is a pending intent which will be triggered when sms is delivered to the target phone.

Example:2

private SmsManager smsManager;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.smsexample);
// . . . other onCreate view item inflation omitted for brevity
smsSend = (Button) findViewById(R.id.smssend_button);
smsManager = SmsManager.getDefault();
final PendingIntent sentIntent =
PendingIntent.getActivity(
this, 0, new Intent(this,
SmsSendCheck.class), 0);
smsSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String dest = smsInputDest.getText().toString();
if (PhoneNumberUtils.
isWellFormedSmsAddress(dest)) {
smsManager.sendTextMessage(
smsInputDest.getText().toString, null,
smsInputText.getText().toString(),
sentIntent, null);
Toast.makeText(SmsExample.this,
"SMS message sent",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SmsExample.this,
"SMS destination invalid - try again",
Toast.LENGTH_LONG).show();
}
}
});
}

 

Before doing anything with SMS messages, we must obtain an instance of the SmsManager with the static getDefault() method . The manager will also send the message later. Before we can send the message, we need to create a PendingIntent to provide to the send method. A PendingIntent can specify an Activity, a Broadcast, or a Service that it requires. In our case, we use the getActivity() method, which requests an Activity, and then we specify the context, a request code (not used for this case), the Intent to execute, and additional flags . The flags indicate whether the system should create a new instance of the referenced Activity (or Broadcast or Service), if one doesn’t already exist. Next, we check that the destination address is valid for SMS , and we send the message using the manager’€™s sendTextMessage() method.

Read More

Make an HTTP request with android

Posted by in Android

Let us retrieve data using HTTP GET requests to a simple HTML page, using the standard java.net API. Then, let us learn to use the Android-included Apache HttpClient API. After we use HttpClient directly to get a feel for it, we wi€™ll also make use of a helper class, HttpRequestHelper, that you can use to simplify the process and encapsulate the details. This class and the Apache networking API in general, has a few advantages over rolling your own networking with java.net, which will be illustrated shortly. The helper class is used to make additional HTTP and HTTPS requests, using GET and POST. We will also look into the basic authentication. First of all, let us take up a HTTP request with an HTTP GET call using HttpUrlConnection.
 
** UPDATE: Android Complete tutorial now available here.
 
GET is the most basic HTTP request method. Here, the data that is sent is embedded in the URL, using the query string. In the Network-Explorer application that is shown below, the next class has an Activity that demonstrates the GET request method.

 

public class SimpleGet extends Activity {
//other portions of onCreate omitted for brevity
this.getButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
getOutput.setText("");
String output = getHttpResponse(getInput.getText().toString());
if (output != null) {
getOutput.setText(output);
}
}
});
};

private String getHttpResponse(String location) {
String result = null;
URL url = null;
try {
url = new URL(location);
} catch (MalformedURLException e) {
// log and or handle
}
if (url != null) {
try {
HttpURLConnection urlConn =
(HttpURLConnection) url.openConnection();
BufferedReader in =
new BufferedReader(
new InputStreamReader(

Invoke getHttpResponse B
method
Construct
URL object
C
Open connection using D
HttpURLConnection
www.it-ebooks.info
Working with HTTP 171
urlConn.getInputStream()));
String inputLine;
int lineCount = 0; // limit lines for example
while ((lineCount < 10)
&& ((inputLine = in.readLine()) != null)) {
lineCount++;
result += "n" + inputLine;
}
in.close();
urlConn.disconnect();
} catch (IOException e) {
// log and or handle
}
} else {
// log and or handle
}
return result;
}
}

The getHttpResponse() method that we’ve built B, is called to get an HTTP response and show the first few lines of it in our SimpleGet class. An object C, of java.net.URL is constructed within this method. A connection to server is opened using an HttpURLConnection D. The object C takes care of many of the details for us here. The BufferedReader is used to read data from the connection one line at a time E. Note that, the same thread that is used for the UI is used here. Hence, the UI is blocked at this point. This is usually not the case and it is used here just for the purpose of demonstrataion. We’ll look into usage of seperate threads shortly. Once the data is received, it is appended to the result string that our method returns F. Then, we close the reader and the connection. A quick and dirty access to HTTP network resources is provided using the plain and simple java.net support that has been ported to Android this way. This way of communicating with HTTP is fairly easy, but can get hard with more complicated data. A few of the problems here can be avoided by spawning separate threads and keeping track of them and by writing your own small framework/API structure around that concept for each HTTP request. But there is a better option. Fortunately, Android provides another set of APIs in the form of the Apache HttpClient3 library that abstract the java.net classes further and are designed to offer more robust HTTP support and help handle the separate-thread issue.

To begin with HttpClient, let us take a look at using core classes to perform HTTP GET and POST method requests. Let us concentrate on making network requests in a Thread separate from the UI, using a combination of the Apache ResponseHandler and Android Handler. Apache HttpClient with Android Handler and Apache ResponseHandler

private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
progressDialog.dismiss();
String bundleResult =
msg.getData().getString("RESPONSE");
output.setText(bundleResult);
}
};
. . . onCreate omitted for brevity
private void performRequest() {
final ResponseHandler<String> responseHandler =
new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) {
StatusLine status = response.getStatusLine();
HttpEntity entity = response.getEntity();
String result = null;
try {
result = StringUtils.inputStreamToString(
entity.getContent());
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("RESPONSE", result);
message.setData(bundle);
handler.sendMessage(message);
} catch (IOException e) {
// log and or handle
}
return result;
}
};
this.progressDialog =
ProgressDialog.show(this, "working . . .",
"performing HTTP request");
new Thread() {
public void run() {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpMethod =
new HttpGet(
urlChooser.getSelectedItem().toString());
client.execute(
httpMethod, responseHandler);
} catch (ClientProtocolException e) {
// log and or handle
} catch (IOException e) {
// log and or handle

First, a Handler is created, which is capable of sending messages to and from other threads. This technique(as used in the previous ex) allows background tasks to send Message objects to hook back into the main UI thread B. Once the Android Handler is created, an Apache ResponseHandler C is created. This class can be used with HttpClient HTTP requests to pass in as a callback point. On completion of the HTTP request that is fired by the HttpClient, the onResponse() method of a ResponseHandler is used. The HttpEntity returned by the API D, is used to get the payload from the response that comes in. Thus, the HTTP call is made in an asynchronous manner. i.e., we don’€™t have to block and wait the entire time between when the request is fired and when it completes. Refer figure 6.3 for the relationship of the request, response, Handler, ResponseHandler, and separate threads This provides a basic understanding of HttpClient at work. Next, we will encapsulate a few of the details into a convenient helper class so that we can call it over and over without having to repeat a lot of the setup.

 

Read More

how to convert apk file to source code

Posted by in Android | 4 comments

 
Step 1:
Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk file to .zip (eg. rename from filename.apk to filename.apk.zip) and save it. Now you get classes.dex files, etc. At this stage you are able to see drawable but not java & xml files, so continue.

 
** UPDATE: Android Complete tutorial now available here.
 

Step 2:
Now extract this zip apk file in the same folder. Now download dex2jar from this link dex2jar and extract it to the same folder. Now open command prompt and change directory to that folder. Then write dex2jar classes.dexand press enter. Now you get classes.dex.dex2jar file in the same folder. Then download java decompiler from this link Java.decompiler.free and now double click on jd-gui and click on open file. Then open classes.dex.dex2jar file from that folder. Now you get class files and save all these class files (click on file then click “save all sources” in jd-gui) by src name. At this stage you get java source but the xml files are still unreadable, so continue to Step 3.
 
Step 3:
Now open another new folder and put these files

  1. Put .apk file which you want to decode
  2. Download apktool v1.x AND apktool install window using Google(http://code.google.com/p/android-apktool/downloads/list) (Very important first download apktool-install-windows-r05-ibot and extract the file . Second download apktool1.5.2, extract jar in that and put it in same folder ) and put in the same folder
  3. Download framework-res.apk file using Google and put in the same folder (Not all apk file need framework-res.apk file)
  4. Open a command window
  5. Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
  6. apktool and "fname".apk (“fname” denotes filename which you want to decode)

 
Now you get a file folder in that folder and now you can easily read xml files also.
 
Step 4:
It’s not any step just copy contents of both folder to the single one and now enjoy with source code.
 

Read More

what is canvas in android

Posted by in Android

 
Canvas is graphics component in android which does the job of calling Draw method and drawing the shape.

According to android documentation , The Canvas class holds the “draw” calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).
 
** UPDATE: Android Complete tutorial now available here.
 

Read More

Uploading file on SFTP Server

Posted by in SFTP Tutorial

 


import java.io.File;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

public class SftpUploadFile {

        public static void main(String[] args) {
                String hostName = "localhost";
                String username = "admin";
                String password = "admin";
                String localFilePath = "C:/myfile.txt";
                String remoteFilePath = "/Myfolder/myfile.txt";

                upload(hostName, username, password, localFilePath, remoteFilePath);
        }
        // Method to upload a file in Remote server
        public static void upload(String hostName, String username,
                        String password, String localFilePath, String remoteFilePath) {

                File file = new File(localFilePath);
                if (!file.exists())
                        throw new RuntimeException("Error. Local file not found");

                StandardFileSystemManager manager = new StandardFileSystemManager();

                try {
                        manager.init();

                        // Create local file object
                        FileObject localFile = manager.resolveFile(file.getAbsolutePath());

                        // Create remote file object
                        FileObject remoteFile = manager.resolveFile(
                           createConnectionString(hostName, username, password,
                                                remoteFilePath), createDefaultOptions());

                        // Copy local file to sftp server
                        remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);

                        System.out.println("File upload success");
                } catch (Exception e) {
                        throw new RuntimeException(e);
                } finally {
                        manager.close();
                }
        }
        
        // Establishing connection
        public static String createConnectionString(String hostName,
        String username, String password, String remoteFilePath) {
        return "sftp://" + username + ":" + password + "@" + hostName + "/"
                                       + remoteFilePath;
        }
        //  Method to setup default SFTP config:
        public static FileSystemOptions createDefaultOptions()
                        throws FileSystemException {
                // Create SFTP options
                FileSystemOptions opts = new FileSystemOptions();

                // SSH Key checking
                SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                                opts, "no");

                // Root directory set to user home
                SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);

                // Timeout is count by Milliseconds
                SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

                return opts;
        }
}

 

Note : Setting the UserDirIsRoot to true , make you to upload file/ Create new folder in current directory. SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);

  Setting it to false , enables you to upload file in any path from root directory.

Read More
Page 10 of 15«First...89101112...Last»