InstantiationException occur while Downloading using Service - android

I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?

Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService

Related

AsyncTask not called in service

Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}

auto call AsyncTask

I have this code, I have 2 AsyncTask I called that by button, and I have one more I want to ask is there any way to call the Asynctask automatic when is open the activity?
I tried to but it with onCreate but it is error
public class SingleCompleteOrder extends ActionBarActivity {
private static final String comp_id = "complete_id";
private static final String comp_table = "complete_table";
private static final String comp_items = "complete_items";
private static final String comp_date = "complete_date";
private TextView oid;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
...
...
...
...
...
}
public void huss() {
Updatsituation task = new Updatsituation ();
task.execute();
}
private class Updatsituation extends AsyncTask<Void,Void,Boolean> {
private ProgressDialog pd;
private Boolean result = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(SingleCompleteOrder.this);
pd.setMessage("Processing commend,Please wait");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(false);
pd.show();
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Utils.WS_UPDATE_SITUAT);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("complete_id", oid.getText().toString()));
mParams.add(new BasicNameValuePair("order_situation","showed"));
try {
post.setEntity(new UrlEncodedFormEntity(mParams));
HttpResponse response = client.execute(post);
String res = EntityUtils.toString(response.getEntity());
Log.d("Order Preview", res);
JSONObject jsonObj = new JSONObject(res);
result = jsonObj.getBoolean("Result");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(Boolean res) {
// TODO Auto-generated method stub
super.onPostExecute(res);
if (pd != null)
pd.dismiss();
if (res) {
Toast.makeText(SingleCompleteOrder.this,
"Order Completed Successfully", Toast.LENGTH_SHORT)
.show();
finish();
Intent intent = new Intent(SingleCompleteOrder.this,
CompleteOrdertest.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(SingleCompleteOrder.this,
"Unable to process the command", Toast.LENGTH_SHORT)
.show();
}
}
}
}
If you want to run the Async task for when the Activity is created you can do this in your OnCreate method. or if you want to execute this every time the Activity come to visibility, you can run this in onResume method.
I do not see you are calling your huss() method in any of your OnCreate or OnResume methods.
EDIT: Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
huss();
...
...
...
...
...
}
If you want to call your AsyncTask, simply do the following within your onCreate() method of the Activity:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// All lines of code
new Updatsituation().execute();
}
This should fire up the task without you having to click any button.
You can put it inside onResume() but then be prepared to have it start everytime your activity resumes.
If you want to call AsyncTask automatically, then you need to call it on OnCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new Updatsituation().execute(); //call your async task
}

Android Shared preference change listener not working even with a global refernce of listener

I have a service which registers a shared preference change listener. The shared preference belongs to another app and is world readable. Despite of keeping a global instance of listener as suggested here, My onSharedPreferenceChanged() is not getting called .
The code of the service is as follows:
public class ClientService extends Service {
public static FileObserver observer;
public static final String addr = "127.0.0.1";
public static final int port = 5001;
public Socket socket = null;
InputStream inputStream;
OutputStream outputStream;
String buffer = new String();
OnSharedPreferenceChangeListener listener;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG, "killing service");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG, "Starting Activity");
Context context = null;
/*try {
socket = new Socket(addr, port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e(MainActivity.TAG, "Error in opening Socket");
}*/
Log.d(MainActivity.TAG,"Carrying on...");
final MyClientTask clientTask = new MyClientTask(addr, port);
SharedPreferences sp = null;
try {
context = getApplicationContext().createPackageContext("net.osmand.plus", Context.MODE_WORLD_WRITEABLE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Log.e(MainActivity.TAG,"OSMAnd Package not found");
}
if(context != null) {
sp = context.getSharedPreferences("net.osmand.settings", Context.MODE_WORLD_READABLE);
Log.d(MainActivity.TAG, ""+sp.getFloat("last_known_map_lat", 0));
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG,"Shared preference "+key+" changed");
if(key == "last_known_map_lat" || key == "last_known_map_lon") {
/* Send this via socket */
float data = sharedPreferences.getFloat(key, 0);
Log.d(MainActivity.TAG, "Sending data: "+data);
clientTask.execute(""+data);
}
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
}
observer = new FileObserver("/data/data/net.osmand.plus/shared_prefs/net.osmand.settings.xml" ) {
#Override
public void onEvent(int event, String path) {
// TODO Auto-generated method stub
if(event == FileObserver.MODIFY) {
Log.d(MainActivity.TAG, "Changed");
}
}
};
return super.onStartCommand(intent, flags, startId);
}
public class MyClientTask extends AsyncTask<String, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(String... buffer) {
try {
byte[] bytes = buffer[0].getBytes();
//outputStream.write(bytes);
Log.d(MainActivity.TAG, "blah");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
The shared preference related code is in onStartCommand().
Anyone has any clue what is wrong ?
Note that in the actual Sharedpreferences file, I can observe the value changing when I see using adb shell
context = getApplicationContext().createPackageContext("net.osmand.plus", Context.MODE_WORLD_WRITEABLE);
your context is null
your con just use "this" service is itself a context
or you can try getSharedPreferences("net.osmand.settings", Context.MODE_WORLD_READABLE);
It seems from this post that what I am trying to do is unsupported in Android. WORLD_READABLE flag for SharedPreferences does not support multi-thread support which might be causing the inconsistencies. In the Android developer site also it is mentioned that multiple process support for SharedPreferences is not available for WORLD_READABLE preferences.

onStartCommand Call after Destroying an Activity

i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue

Error in running a thread from inside a timertask (running inside a Thread) present in a Service

I have a Service which runs a thread. This thread runs a timertask, this timertask now has to run another thread.
My Service class looks like this:
Timer pTimer;
int Time = 1;
int samplerate=100;
int sampleSize=((Time*1000)/samplerate);
Accelerometer_Thread Ac_Thread;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
pTimer = new Timer();
Ac_Thread = new Accelerometer_Thread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
//super.onStart(intent, startId);
Ac_Thread.start();
return START_STICKY;
}
public class Accelerometer_Thread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
pTimer.scheduleAtFixedRate(task,0, samplerate);
}
}
/* The Timertask which is to be executed at a periodic interval of "samplerate" */
TimerTask task = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
String Ack = null;
try {
Ack = Post.PostToWebService("Hello");
} catch (Exception e) {
// TODO Auto-generated catch block
}
if (Ack.contentEquals("1")) {
//Do SOmething
}
else
Log.d("Error", "NotSent To Webservice");
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
};
The Post.PostToWebService which starts the Thread looks like this:
public static String ReceivedAcknowledgement=null;
public static String buffer;
public static String PostToWebService(String Payload){
CallPost cp = new CallPost();
buffer = Payload;
ReceivedAcknowledgement="STRT";
try {
cp.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cp.start();
while(ReceivedAcknowledgement=="STRT")
{
try
{
Thread.sleep(10);
}catch(Exception ex)
{
}
}
if(ReceivedAcknowledgement != "STRT")
return ReceivedAcknowledgement;
else
return null;
}
The CallPost looks like this:
public class CallPost extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
Post.ReceivedAcknowledgement = ParseXML(in);
}
private String ParseXML(InputStream i){
//Parse
}
}
I'm getting an error in my Service class at the line Post.PostToWebService("Hello") where the error says:
java.lang.RuntimeException: Can't create handler inside thread that
has not called Looper.prepare()
I've tried understanding about loopers and handlers but I'm not able to get it.

Categories

Resources