Sunteți pe pagina 1din 33

ANDROIDMANIFEST.XML <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.msk.smartcomplaint" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> <activity android:name=".

MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ComplaintActivity"></activity> <service android:name="UploadService"></service> </application> <uses-permission android:name="android.permission.CAMERA"></uses-permission> <uses-sdk android:minSdkVersion="7"></uses-sdk> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></usespermission> <uses-permission android:name="android.permission.INTERNET"></usespermission> </manifest>

MAINACTIVITY PART

package com.msk.smartcomplaint;

import android.app.Activity; import android.content.Intent; import android.os.Bundle;

import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener { /** Called when the activity is first created. */ private Button bwssbB, bescomB, policeB, trafficB , bbmpB, exitB; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.homepage);

bwssbB = (Button) findViewById(R.id.bwssbB); bescomB = (Button) findViewById(R.id.bescomB); policeB = (Button) findViewById(R.id.policeB); trafficB = (Button) findViewById(R.id.trafficB); bbmpB = (Button) findViewById(R.id.bbmpB); exitB = (Button) findViewById(R.id.exitB);

bwssbB.setOnClickListener(this); bescomB.setOnClickListener(this); policeB.setOnClickListener(this); trafficB.setOnClickListener(this); bbmpB.setOnClickListener(this); exitB.setOnClickListener(this);

} @Override public void onClick(View v) { // TODO Auto-generated method stub int code=0; if(v!=exitB) { if(v == bwssbB) code = 3; else if (v== bescomB) code = 1; else if (v == policeB) code = 4; else if(v == trafficB) code = 2; else if(v== bbmpB) code =5;

Intent i = new Intent(this, ComplaintActivity.class); i.putExtra("code", code); startActivity(i); } else finish(); }

FOR LEARNING FULL CODE AND IMPLEMETATION CONTACT MASTERSKILLS9845914151


RESTCLIENT.JAVA package com.msk.smartcomplaint; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams;

import android.util.Log;

public class RestClient {

private String url; private String requestXml;

private int responseCode; private String message;

private String response;

public String getResponse() { return response; }

public String getErrorMessage() { return message; }

public int getResponseCode() { return responseCode; }

public RestClient(String url, String requestxml) { this.url = url; this.requestXml = requestxml;

// out of the requestXml forms HttpPost request public void Execute() throws Exception {

HttpPost request = new HttpPost(url);

//String xml="<IncomingRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ClientRequest><![CDATA[" +

//"<FriendLocator><MobileNumber>8105893939</MobileNumber></FriendLocator>]]></Client Request></IncomingRequest>";

byte currentbyte[] = requestXml.getBytes(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentbyte); InputStreamEntity reqEntity = new InputStreamEntity(byteArrayInputStream, currentbyte.length); reqEntity.setContentType("text/xml");

request.setEntity(reqEntity);

Log.d("RestClient", request.toString()); executeRequest(request, url);

// sets HTTP request parameters, sends request to given URL and obtains response. private void executeRequest(HttpUriRequest request, String url) {

// HttpClient client = new DefaultHttpClient();

HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 50000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 50000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient client = new DefaultHttpClient(httpParameters);

HttpResponse httpResponse;

try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase();

Log.d("RestClient", "responseCode="+responseCode+"\nmessage="+message);

HttpEntity entity = httpResponse.getEntity();

if (entity != null) {

InputStream instream = entity.getContent(); response = convertStreamToString(instream);

// Closing the input stream will trigger connection release instream.close(); }

} catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); // e.printStackTrace(); Log.e("RestClient", e.getMessage()); } catch (IOException e) { client.getConnectionManager().shutdown(); Log.e("RestClient", e.getMessage()); } }

// reads the inputStream line by line and returns the appended string. private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder();

String line = null;

try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }

COMPALINT ACTIVITY.JAVA

package com.msk.smartcomplaint;

import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; //import android.util.Base64;

import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle;

import android.os.Environment; import android.provider.MediaStore; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast;

public class ComplaintActivity extends Activity implements OnClickListener { private static final int TAKE_PICTURE = 1; private Button pictureB, registerB; private EditText remarksE; private ImageView iv; private Location currentLocation = null; private LocationManager locationManager; private int category; private String LOCATION_PROVIDER = null; protected final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 25; // in Meters protected final long MINIMUM_TIME_BETWEEN_UPDATE = 5 * 60 * 1000; // in

// Milliseconds

protected LocationListener listener;

private String mPhoneNumber; private int priority; private boolean isPicTaken;

@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.complaint2);

this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> l = locationManager.getProviders(true); if (l.contains(LocationManager.NETWORK_PROVIDER)) LOCATION_PROVIDER = LocationManager.NETWORK_PROVIDER; else if (l.contains(LocationManager.GPS_PROVIDER)) LOCATION_PROVIDER = LocationManager.GPS_PROVIDER; // LOCATION_PROVIDER = strProvider; Log.d("provider", "prv is " + LOCATION_PROVIDER); Toast .makeText(this, "provider=" + LOCATION_PROVIDER, Toast.LENGTH_LONG).show();

Intent i = getIntent(); category = i.getIntExtra("code", 1);

pictureB = (Button) findViewById(R.id.pictureB); registerB = (Button) findViewById(R.id.registerB); remarksE = (EditText) findViewById(R.id.remarksE); iv = (ImageView) findViewById(R.id.picTaken);

pictureB.setOnClickListener(this); registerB.setOnClickListener(this);

listener = new myLocationListener(); this.locationManager.requestLocationUpdates(LOCATION_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATE, MINIMUM_DISTANCECHANGE_FOR_UPDATE, listener); currentLocation = locationManager .getLastKnownLocation(LOCATION_PROVIDER);

TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mPhoneNumber = tMgr.getLine1Number();

Log.d("SmartComplaint", "Phone=" + mPhoneNumber); }

@Override public void onClick(View v) {

if (v == pictureB) takePicture(); else if (v == registerB) //registerComplaint(); { removeDialog(1); showDialog(1); } }

private void registerComplaint() { // TODO Auto-generated method stub

String remarks = remarksE.getText().toString(); // String priority ="normal"; // todo: show dialog for asking priority

if(!isPicTaken) { Toast.makeText(this, "Please capture picture!!", Toast.LENGTH_LONG).show(); return; } if (remarks.length() > 0) { Intent i = new Intent(this, UploadService.class); i.putExtra("remarks", remarks); i.putExtra("priority", priority + 1);

i.putExtra("category", category); i.putExtra("mobilenumber", mPhoneNumber); i.putExtra("photo", "/sdcard/shree.jpg");

// removeDialog(1); if (currentLocation != null) {

Toast.makeText(this, "Long="+currentLocation.getLongitude()+"\nLat="+currentLocation.getLatitude(), Toast.LENGTH_LONG).show();

i.putExtra("longitude", currentLocation.getLongitude()); i.putExtra("lattitude", currentLocation.getLatitude());

} else { Toast.makeText(this,"location not available.. Registering without location", Toast.LENGTH_LONG).show();

} startService(i); finish(); } else { Toast.makeText(this, "Please enter remarks", Toast.LENGTH_LONG) .show(); } }

private static final int PRIORITY_DLG = 1;

@Override protected Dialog onCreateDialog(int id) { // TODO Auto-generated method stub // return super.onCreateDialog(id);

Dialog dlg = null;

switch (id) { case PRIORITY_DLG: { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Priority");

final String[] list = { "High", "Medium", "low" }; builder.setSingleChoiceItems(list, 0, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub priority = which; registerComplaint(); dialog.cancel();

} }); builder.setCancelable(false);

dlg = builder.create(); } }

return dlg; }

private void takePicture() { // TODO Auto-generated method stub isPicTaken =false; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

Uri outputFileUri = Uri.parse("file:///sdcard/shree.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(intent, TAKE_PICTURE);

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == TAKE_PICTURE) { if (resultCode == RESULT_OK) { if (data == null) { isPicTaken= true; BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; /*if(data.hasExtra("data")) { Log.d("ComplaintActivity", "data has extra"); Bitmap thumbnail = data.getParcelableExtra("data"); iv.setImageBitmap(thumbnail); // TODO do something with thumbnail }*/

/*Uri u = data.getData(); Toast.makeText(this, "uri="+u, Toast.LENGTH_LONG).show(); InputStream myInStream; try { myInStream = getContentResolver().openInputStream(u); Bitmap v = BitmapFactory.decodeStream(myInStream); iv.setImageBitmap(v); } catch (Exception e) { // TODO Auto-generated catch block

//e.printStackTrace(); Log.d("ComplaintActivity", "exception:"+e); Toast.makeText(this, "Exception "+e.getMessage(), Toast.LENGTH_LONG).show(); } */

Bitmap bitmapOrg = BitmapFactory.decodeFile("/sdcard/shree.jpg",options);

iv.setImageBitmap(bitmapOrg); } } } }

class myLocationListener implements LocationListener {

@Override public void onLocationChanged(Location location) {

currentLocation = location;

@Override public void onProviderDisabled(String provider) {

// TODO Auto-generated method stub

@Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub

@Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub

UPLOADSERVICE.JAVA package com.msk.smartcomplaint;

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;

import java.text.SimpleDateFormat; import java.util.Date;

import com.msk.util.Base64;

import android.app.Service; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.os.Handler; import android.os.IBinder; //import android.util.Base64; import android.util.Log; import android.widget.Toast;

public class UploadService extends Service { private String remarks; private int priority; private double longi; private double latti; private String imageName; private String number; private int category;

private Handler uiHandler = new Handler(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; }

@Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); if(intent!=null) { number=intent.getStringExtra("mobilenumber"); longi = intent.getDoubleExtra("longitude", 0); latti = intent.getDoubleExtra("lattitude", 0); remarks = intent.getStringExtra("remarks"); priority = intent.getIntExtra("priority",1); category = intent.getIntExtra("category", 0); imageName = intent.getStringExtra("photo");

//Toast.makeText(this, "Number in service="+number+"\nimage:"+imageName, Toast.LENGTH_LONG).show();

Thread t = new Thread(runner); t.start(); } }

private class MyRunnable implements Runnable{ private String message=null;

public MyRunnable(String message) { // TODO Auto-generated constructor stub this.message=message; } public void run() { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } };

private String createXml() { // TODO Auto-generated method stub String xml = "<IncomingRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchemainstance\" " +

"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ClientRequest><![CDATA[<SmartCompl aint>" + "<MobileNumber>";

String part2="</MobileNumber><Longitude>"; String part3="</Longitude><Lattitude>"; String part4="</Lattitude><Time>";//12/10/2011 String part5="</Time><Category>"; String part6="</Category><Priority>"; String part7="</Priority><FileName>"; String part8 = "</FileName><Image>"; String part9="</Image><Remarks>"; String part10="</Remarks>" + "</SmartComplaint>]]></ClientRequest></IncomingRequest>";

Date d = new Date();

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");

String time = formatter.format(d); String imageData = getBase64ImageData();

SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");

String filename = "image"+fileNameFormatter.format(d)+".jpg"; return xml+number+part2+longi+part3+latti+part4+time+part5+category+part6+priority+ part7+filename+part8+imageData+part9+remarks+part10; //return xml+"9845914151"+part2+longitude+part3+lattitude+part4+time+part5;

private String getBase64ImageData() { // TODO Auto-generated method stub

BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap bitmapOrg = BitmapFactory.decodeFile(imageName,options); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte [] ba = bao.toByteArray();

//String data = Base64.encodeToString(ba, 0); String data = Base64.encode(ba); Log.d("UploadService", data); bitmapOrg=null; System.gc(); return data; }

private Runnable runner = new Runnable() {

@Override

public void run() { // TODO Auto-generated method stub if(number !=null) { // create request xml String xml = createXml();

RestClient client = new RestClient("http://www.myprojectideas.in/SmartCompService/SmartComplaint.svc/SmartComplaintRes ponse",xml);

Log.d("UploadService", xml);

//writeToFile(xml);

try { client.Execute(); String response = client.getResponse();

String str1="<SmartComplaint><Status>"; // String str2="</Status></SmartComplaint>";

String code =response.substring(str1.length(),str1.length()+1 ); Log.d("UploadService", "response="+response+",code="+code); if(code.equalsIgnoreCase("0")) {

MyRunnable r = new MyRunnable("Your complaint has been registered successfully"); uiHandler.post(r);

} } catch (Exception e) { //e.printStackTrace(); Log.e("UploadService", "Exception:"+e.getMessage()); MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage()); uiHandler.post(r);

} }

};

package com.msk.util; public class Base64 { private Base64() { super(); } /** * Encode some data and return a String. */ public final static String encode(byte[] d) { if (d == null) return null; byte data[] = new byte[d.length+2]; System.arraycopy(d, 0, data, 0, d.length); byte dest[] = new byte[(data.length/3)*4]; // 3-byte to 4-byte conversion for (int sidx = 0, didx=0; sidx < d.length; sidx += 3, didx += 4) { dest[didx] = (byte) ((data[sidx] >>> 2) & 077); dest[didx+1] = (byte) ((data[sidx+1] >>> 4) & 017 | (data[sidx] << 4) & 077); dest[didx+2] = (byte) ((data[sidx+2] >>> 6) & 003 | (data[sidx+1] << 2) & 077); dest[didx+3] = (byte) (data[sidx+2] & 077); } // 0-63 to ascii printable conversion for (int idx = 0; idx <dest.length; idx++) { if (dest[idx] < 26) dest[idx] = (byte)(dest[idx] + 'A'); else if (dest[idx] < 52) dest[idx] = (byte)(dest[idx] + 'a' - 26); else if (dest[idx] < 62) dest[idx] = (byte)(dest[idx] + '0' - 52); else if (dest[idx] < 63) dest[idx] = (byte)'+'; else dest[idx] = (byte)'/'; } // add padding for (int idx = dest.length-1; idx > (d.length*4)/3; idx--) { dest[idx] = (byte)'='; } return new String(dest); } /** * Encode a String using Base64 using the default platform encoding **/ public final static String encode(String s) {

return encode(s.getBytes()); } /** * Decode data and return bytes. */ public final static byte[] decode(String str) { if (str == null) return null; byte data[] = str.getBytes(); return decode(data); } /** * Decode data and return bytes. Assumes that the data passed * in is ASCII text. */ public final static byte[] decode(byte[] data) { int tail = data.length; while (data[tail-1] == '=') tail--; byte dest[] = new byte[tail - data.length/4]; // ascii printable to 0-63 conversion for (int idx = 0; idx <data.length; idx++) { if (data[idx] == '=') data[idx] = 0; else if (data[idx] == '/') data[idx] = 63; else if (data[idx] == '+') data[idx] = 62; else if (data[idx] >= '0' && data[idx] <= '9') data[idx] = (byte)(data[idx] - ('0' - 52)); else if (data[idx] >= 'a' && data[idx] <= 'z') data[idx] = (byte)(data[idx] - ('a' - 26)); else if (data[idx] >= 'A' && data[idx] <= 'Z') data[idx] = (byte)(data[idx] - 'A'); } // 4-byte to 3-byte conversion int sidx, didx; for (sidx = 0, didx=0; didx < dest.length-2; sidx += 4, didx += 3) { dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 3) ); dest[didx+1] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) ); dest[didx+2] = (byte) ( ((data[sidx+2] << 6) & 255) | (data[sidx+3] & 077) ); } if (didx < dest.length) { dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 3) ); } if (++didx < dest.length) { dest[didx] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) );

} return dest; } /** * A simple test that encodes and decodes the first commandline argument. */ public static final void main(String[] args) { if (args.length != 1) { System.out.println("Usage: Base64 string"); System.exit(0); } try { String e = Base64.encode(args[0].getBytes()); String d = new String(Base64.decode(e)); System.out.println("Input = '" + args[0] + "'"); System.out.println("Encoded = '" + e + "'"); System.out.println("Decoded = '" + d + "'"); } catch (Exception x) { x.printStackTrace(); } } }

FOR LEARNING FULL CODE AND IMPLEMETATION

CONTACT MASTERSKILLS9845914151

S-ar putea să vă placă și