I want to update my location on server using service but i am not getting why my service is not running. here is code:
package com.example.friendlocation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateLocationService extends Service {
String url = "http://coders-hub.com/googlemap/new/location.php";
JSONParser jsonParser = new JSONParser();
String id;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent==null || intent.getAction()==null)
return START_NOT_STICKY;
Toast.makeText(getApplicationContext(), "In onCreate()!", Toast.LENGTH_SHORT).show();
SharedPreferences sp=getSharedPreferences("location", Activity.MODE_PRIVATE);
id=sp.getString("id", null);
if(id!=null)
{
Toast.makeText(getApplicationContext(), "In id!", Toast.LENGTH_SHORT).show();
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c=new Criteria();
String provider=lm.getBestProvider(c, false);
lm.requestLocationUpdates(provider, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("lat", location.getLatitude()+""));
params.add(new BasicNameValuePair("longi", location.getLongitude()+""));
JSONObject json=jsonParser.makeHttpRequest(url,"POST", params);
Toast.makeText(getApplicationContext(), "In onLocationChanged()!", Toast.LENGTH_SHORT).show();
try {
int success = json.getInt("success");
if (success == 1)
Toast.makeText(getApplicationContext(), "Updated in Service!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "Not updated in Service!", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error in JsonException Service!", Toast.LENGTH_SHORT).show();
}
}
});
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
I added permissions in AndroidManifast.xml file and declare Service like this:
<service android:name="com.example.friendlocation.UpdateLocationService">
</service>
And calling it from listener class:
Intent i=new Intent(context, UpdateLocationService.class);
context.startService(i);
But service is not starting.
Related
how can i keep the socket active on the service, when i close the app it disconnected, from node, i call it from the main activity, with startService(new Intent(this, sys_service.class)); the socket its fine while the app its active
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class sys_service extends Service {
Socket mSocket;
TelephonyManager manager;
JSONObject chat_response;
private Handler mHandler = new Handler();
String msg_over;
{
try {
mSocket = IO.socket("http://xxxx:8001");
} catch (URISyntaxException e) {
Toast.makeText(this, "refused", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Toast.makeText(this,"Service Active :)", Toast.LENGTH_LONG ).show();
run_app();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service stop :)", Toast.LENGTH_LONG ).show();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent){
run_app();
return null;
}
public Socket getSocket() {
return mSocket;
}
public void run_app() {
mSocket.connect();
manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final JSONObject uidJson = new JSONObject();
String real = manager.getDeviceId();
try {
uidJson.put("uid", real);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.on("connect", new Emitter.Listener() {
public void call(Object... args) {
mSocket.emit("uid", uidJson);
}
});
mSocket.on("chat", new Emitter.Listener() {
public void call(Object... args) {
String chat_msg = args[0].toString();
try {
chat_response = new JSONObject(chat_msg);
} catch (JSONException e) {
e.printStackTrace();
}
msg_over = chat_response.optString("msg");
final JSONObject chat = new JSONObject();
try {
chat.put("msg", "all fine");
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("test", msg_over);
//Toast.makeText(StartActivity.this, msg, Toast.LENGTH_SHORT).show(); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Log.d("chat", msg_over);
}
});
}
}
i am creating sip application. i am testing it on my micromax a26 and it has android 2.3.5 and i am having problems
-->1
when i am executing this code
if(SipManager.isApiSupported(getApplicationContext()))
Toast.makeText(getApplicationContext(), "support", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "not support", Toast.LENGTH_SHORT).show();
i am getting "not support" alert.
in this http://developer.android.com/guide/topics/connectivity/sip.html it says i need You must have a mobile device that is running Android 2.3 or higher.
what i am missing???
-->2
at this line
if(manager == null) {
manager = SipManager.newInstance(this);
}
if (manager == null) {
Toast.makeText(getApplicationContext(), "manager null", Toast.LENGTH_SHORT).show();
return;
}
i am again getting alert "manager null" so i can guess that SipManager.newInstance(this) is retuning null. see this http://developer.android.com/reference/android/net/sip/SipManager.html#newInstance%28android.content.Context%29
this is my whole code
package com.archish;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.*;
import android.net.sip.*;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.text.ParseException;
public class SipTestActivity extends Activity implements View.OnTouchListener{
public String sipAddress;
public static SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call =null;
//public IncomingCallReceiver callReceiver;
EditText Domain;
EditText UId;
EditText Pwd;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Domain=(EditText)findViewById(R.id.edtDomain);
UId=(EditText)findViewById(R.id.edtUid);
Pwd=(EditText)findViewById(R.id.edtPwd);
if(SipManager.isApiSupported(getApplicationContext()))
Toast.makeText(getApplicationContext(), "support", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "not support", Toast.LENGTH_SHORT).show();
IntentFilter filter = new IntentFilter();
filter.addAction("com.archish.INCOMING_CALL");
initializeManager();
/*Button Reg=(Button)findViewById(R.id.btnReg);
Reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "on click ", Toast.LENGTH_SHORT).show();
try {
Register();
} catch (SipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});*/
}
private void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(getBaseContext());
}
Register();
}
public void Register()
{
if (manager == null) {
Toast.makeText(getApplicationContext(), "manager null", Toast.LENGTH_SHORT).show();
return;
}
if (me != null) {
closeLocalProfile();
}
try{
SipProfile.Builder builder = new SipProfile.Builder("1001", "123");
builder.setPassword("1234");
me = builder.build();
Intent i = new Intent();
i.setAction("com.archish.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
Toast.makeText(getApplicationContext(), "Registering with SIP Server...", Toast.LENGTH_SHORT).show();
// updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
Toast.makeText(getApplicationContext(), "reaDy", Toast.LENGTH_SHORT).show();
// updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
Toast.makeText(getApplicationContext(), "Registration failed. Please check settings.", Toast.LENGTH_SHORT).show();
// updateStatus("Registration failed. Please check settings.");
}
});
}
catch (ParseException pe) {
//updateStatus("Connection Error.");
} catch (SipException se) {
//updateStatus("Connection error.");
}
}
private void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
please help me !!! i am new in android, give me any hint to solve this... what is the problem????
I am updating location details on server using service and it works fine if my app is opened otherwise it is giving error in service's starting time.."Unfortunately your app has stopped."
package com.example.friendlocation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateLocationService extends Service {
String url = "http://znsoftech.com/googlemap/new/location.php";
JSONParser jsonParser = new JSONParser();
String id;
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "In onCreate()!", Toast.LENGTH_SHORT).show();
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "In onStart()!", Toast.LENGTH_SHORT).show();
getresult();
}
private void getresult() {
// TODO Auto-generated method stub
SharedPreferences sp=getSharedPreferences("location", Activity.MODE_PRIVATE);
id=sp.getString("id", null);
if(id!=null)
{
Toast.makeText(getApplicationContext(), "In id!"+id, Toast.LENGTH_SHORT).show();
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c=new Criteria();
String provider=lm.getBestProvider(c, false);
lm.requestSingleUpdate(provider, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("lat", location.getLatitude()+""));
params.add(new BasicNameValuePair("longi", location.getLongitude()+""));
JSONObject json=jsonParser.makeHttpRequest(url,"POST", params);
Toast.makeText(getApplicationContext(), "In onLocationChanged()!", Toast.LENGTH_SHORT).show();
try {
int success = json.getInt("success");
if (success == 1)
{
Toast.makeText(getApplicationContext(), "Updated in Service!", Toast.LENGTH_SHORT).show();
stopSelf();
}
else
Toast.makeText(getApplicationContext(), "Not updated in Service!", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error in JsonException Service!", Toast.LENGTH_SHORT).show();
stopSelf();
}
}
},null);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if(intent==null || intent.getAction()==null)
return Service.START_NOT_STICKY;
Toast.makeText(getApplicationContext(), "In onStartCommand()!", Toast.LENGTH_SHORT).show();
getresult();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Added all permission in AndroidManifast.xml file. Where I am doing wrong? Should i have to use AsyncTask to update location in background?
If its because of NULLPOINTER EXCEPTION then please do add null safety for location object.I had faced similar kind of problem in nexus device.
if(location != null){
latitude = location.getLatitude();
}
I have set orientation of my activity to landscape and it remains in that state except one case.and the case is screen lock .when my activity is running and i lock my screen it changes orientation from landscape to portrait for little bit of time and causes my app to restart and which I don't want.any solution...?
package com.example.hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity{
VideoView vv;
public ArrayList<String> list = new ArrayList<String>();
int n,positio = 0;
String file = null;
Spinner spin;
MediaPlayer mp;
Intent intent;
File fl;
boolean isPlaying = true;
boolean screenOn = false;
PowerManager pm;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Log.d("zaid iqbal", "in onCreate");
requestFullScreen();
setContentView(R.layout.activity_main);
vv = (VideoView)findViewById(R.id.video);
spin = (Spinner)findViewById(R.id.spinner);
MediaController mc = new MediaController(this);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
vv.setMediaController(mc);
setupSpin();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onPause");
isPlaying = vv.isPlaying();
screenOn = pm.isScreenOn();
if (screenOn && isPlaying) {
// Screen is still on, so do your thing here
n++;
positio = vv.getCurrentPosition();
vv.pause();
//Toast.makeText(this, file, Toast.LENGTH_LONG).show();
intent = new Intent(this,playBack.class);
intent.putExtra("file", file);
intent.putExtra("position", positio);
intent.putExtra("n", n);
startService(intent);
}
if(!isPlaying){
positio = vv.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onResume");
if(!isPlaying){
vv.setVideoPath(file);
vv.seekTo(positio);
}else{
async aa = new async();
aa.execute();
}
super.onResume();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
public void requestFullScreen(){
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void setupSpin(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/");
listFiles(root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//Log.d("zaid iqbal","in onclick of spin");
if(n == 0){
file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/" + list.get(position);
Log.d("zaid", file);
//Toast.makeText(MainActivity.this, "original" + file, Toast.LENGTH_SHORT).show();
vv.setVideoPath(file);
vv.start();
}
//n = 0;
/*File fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
position = Integer.parseInt(reader.readLine());
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file);
writer.write(position);
writer.write(n);
position = Integer.parseInt(reader.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void listFiles(File f){
try{
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String filenameArray[] = file.toString().split("\\.");
String extension = filenameArray[filenameArray.length-1];
//if(extension == "mp4" || extension == "3gp")
list.add(file.getName());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
class async extends AsyncTask<String,Long,Long>{
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
if(intent != null){
stopService(intent);
//Reading file
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
//Log.d("zaid iqbal", "getted file");
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
//Toast.makeText(MainActivity.this, "getted file" + file, Toast.LENGTH_SHORT).show();
positio = Integer.parseInt(reader.readLine());
n = Integer.parseInt(reader.readLine());
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n != 0){
n=0;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file + "\n" + positio + "\n" + n);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vv.setVideoPath(file);
vv.seekTo(positio);
vv.start();
}
super.onPostExecute(result);
}
}
}
First, I would read up on Android activity lifecycle. Personally I think this is the way begin to address the issue -
http://developer.android.com/training/basics/activity-lifecycle/index.html
Another option to investigate -
android:configChanges="orientation|keyboardHidden|screenSize"
how to stop activity recreation on screen orientation?
Try this in your Activity Tag of Manifest file :
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Here Orientation refers to Configuration changes which you want to handle by your own.
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle.
Use onSaveInstanceState() and onRestoreInstanceState() if you want to restore your previous state of an activity.
Refer this also
You may try to call setRequestedOrientation() in you activity so the orientation is forced.
I am developing an application in android wrein I call a service that will upload a xml file to the server on click of a button.Problem is when I click the button first time it dosent get uploaded but when I click the button second time its gets uploaded...so let me know if there is any solution..pls help me.
Here is code below which extends service
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
public class Uploader extends Service
{
String info;
String phot_loc;
int category;
String phonenumber = null,profile_name=null,email_id=null;
double longi;
double latti;
Runnable runner;
//UIhandler to display the status of upload on response from server
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)
{
info=intent.getStringExtra("info");
phot_loc=intent.getStringExtra("photo_loc");
category=intent.getIntExtra("category",0);
phonenumber=intent.getStringExtra("phone_number");
profile_name=intent.getStringExtra("profile_name");
email_id=intent.getStringExtra("email_id");
longi=intent.getDoubleExtra("longitude",0);
latti=intent.getDoubleExtra("latitude",0);
phonenumber=intent.getStringExtra("phone_number");
Log.d("UploadService","Indide upload Activity");
Thread t=new Thread(runner);
t.start();
}
//this will perform the uploading process
runner=new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Log.d("UploadService","Indide upload Activity RIUNNER");
String xml = createXml();
RestClient client = new RestClient("http://3pixelart.com/complaint_process.php",xml);
//Log.d("UploadService", xml);
try {
client.Execute();
MyRunnable r = new MyRunnable("Complaint Uploaded Successfully");
uiHandler.post(r);
}
catch(Exception e)
{
Log.e("UploadService", "Exception in uploading :"+e.getMessage());
MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage());
uiHandler.post(r);
}
}
catch(Exception e)
{
Log.e("UploadService", "Exception:"+e.getMessage());
MyRunnable r=new MyRunnable("Error in uploading the complaint..");
uiHandler.post(r);
}
}
};
}
public String createXml() {
Log.d("UploadService","Indide upload Activity create xml 1");
Log.d("UploadService","Indide upload Activity create xml 2");
Date d = new Date();
//SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
//String time = formatter.format(d);
Log.d("UploadService","Indide upload Activity create xml 3");
String imageData = getBase64ImageData();
SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");
Log.d("UploadService","Indide upload Activity create xml 5");
String filename = "image"+fileNameFormatter.format(d)+".png";
String finaldata="<?xml version=\"1.0\"?>";
finaldata+="<ClientRequest><MobileNumber>"+phonenumber+"</MobileNumber><Longitude>";
finaldata+=longi+"</Longitude><Lattitude>"+latti+"</Lattitude>";
finaldata+="<Category>"+category+"</Category>";
finaldata+="<Profilename>"+profile_name+"</Profilename><Email>"+email_id+"</Email>";
finaldata+="<FileName>"+filename+"</FileName><Image>"+imageData+"</Image><Info>";
finaldata+=info+"</Info></ClientRequest>";
Log.d("UploadService","The DATA IS : "+finaldata);
return finaldata;
}
private String getBase64ImageData() {
// TODO Auto-generated method stub
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapOrg = BitmapFactory.decodeFile(phot_loc,options);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedImage = Base64.encodeToString(ba, Base64.DEFAULT);
//Log.d("UploadService", encodedImage);
bitmapOrg=null;
System.gc();
return encodedImage;
}
//this is used to display the status of uploading for this u require UIHandler
public 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();
}
};
}
and this is my activity which strats that service
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
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
{
boolean pic_taken=false;
Button bpicture,bregister;
EditText description;
ImageView iv1;
int category=0;
private static final int TAKE_PICTURE = 1;
String Provider_name="";
Location currentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint);
bpicture=(Button) findViewById(R.id.button1);
bregister=(Button) findViewById(R.id.button2);
iv1=(ImageView) findViewById(R.id.taken_pic);
description=(EditText)findViewById(R.id.editText1);
bpicture.setOnClickListener(ComplaintActivity.this);
bregister.setOnClickListener(ComplaintActivity.this);
LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
List <String> l1=manager.getProviders(true);
if(l1.contains(LocationManager.GPS_PROVIDER))
{
Provider_name=LocationManager.GPS_PROVIDER;
}
if(l1.contains(LocationManager.NETWORK_PROVIDER))
{
Provider_name=LocationManager.NETWORK_PROVIDER;
}
currentLocation=manager.getLastKnownLocation(Provider_name);
Toast.makeText(ComplaintActivity.this, "GPS PROVIDERS "+Provider_name+"Lattti:"+currentLocation.getLatitude()+"Long:"+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
LocationListener listener=new MyLocationListener();
manager.requestLocationUpdates(Provider_name, 0, 0, listener);
}
class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
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
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0==bpicture)
take_picture();
if(arg0==bregister)
register_complaint();
}
private void take_picture() {
// TODO Auto-generated method stub
Intent int_cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri Outputfile=Uri.parse("file:///sdcard/temppic.jpg");
int_cam.putExtra(MediaStore.EXTRA_OUTPUT,Outputfile);
startActivityForResult(int_cam,TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//Log.d("BAKRA","INSIDE CAMEra Activity>>>>>>>>>>>");
if(requestCode==1)
{
//Log.d("BAKRA","INSIDE FIRST IF >>>>>>>>>>>");
if(resultCode==RESULT_OK)
{
// Log.d("BAKRA","INSIDE SECONG IF >>>>>>>>>>>");
if(data==null)
{
// Log.d("BAKRA","INSIDE THIRD IF >>>>>>>>>>>");
pic_taken=true;
BitmapFactory.Options opt=new BitmapFactory.Options();
opt.inSampleSize=8;
Bitmap bitorg=BitmapFactory.decodeFile("sdcard/temppic.jpg", opt);
// Log.d("BAKRA","INSIDE CAME>>>>>>>>>>>");
iv1.setImageBitmap(bitorg);
}
}
}
}
private void register_complaint() {
// TODO Auto-generated method stub
if(!pic_taken)
{
Toast.makeText(ComplaintActivity.this, "Please Take the Picture Related to the Query", Toast.LENGTH_LONG).show();
return;
}
if(description.getText().toString().equals(""))
{
Toast.makeText(ComplaintActivity.this, "Please Enter Details About the Complaint",Toast.LENGTH_LONG).show();
return;
}
else
{
Intent up=new Intent(ComplaintActivity.this,Uploader.class);
up.putExtra("category",getIntent().getIntExtra("Selected",1));
up.putExtra("info", description.getText().toString());
up.putExtra("photo_loc", "/sdcard/temppic.jpg");
up.putExtra("latitude", currentLocation.getLatitude());
up.putExtra("longitude", currentLocation.getLongitude());
SQLiteDatabase db=openOrCreateDatabase("LBA", MODE_PRIVATE, null);
Cursor c=db.rawQuery("select * from users", null);
String phonenumber = null,profile_name=null,email_id=null;
if(c.moveToFirst())
{
profile_name=c.getString(c.getColumnIndex("profilename"));
email_id=c.getString(c.getColumnIndex("emailid"));
phonenumber=c.getString(c.getColumnIndex("phonenumber"));
}
up.putExtra("phone_number", phonenumber);
up.putExtra("profile_name", profile_name);
up.putExtra("email_id", email_id);
startService(up);
Toast.makeText(ComplaintActivity.this, "Uploading to Server...",Toast.LENGTH_LONG).show();
finish();
}
}
}
onStartCommand intent:
This may be null if the service is being restarted after its process
has gone away, and it had previously returned anything except
START_STICKY_COMPATIBILITY.
http://developer.android.com/reference/android/app/Service.html
So try use:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
rather than finish();