I have problem how to call my method in a service, my method is getambil_jmlgangguan().
Detailed code is here :
public class GetCountDataGangguanService extends Service {
public String JUMLAH_GANGGUAN ="";
public static final String TAG = "MyServiceTag1";
GlobalKoneksi konek_url = new GlobalKoneksi();
GetJmlGangguanFunction jmlGangguanFUnctions = new GetJmlGangguanFunction();
private static String KEY_SUCCESS = "success";
private static String KEY_JUMLAH_DATA = "jumlah";
JSONArray jml_data_json = null;
// UserFunctions userFunctions;
UserFunctions userFunctions = new UserFunctions();
SessionManager session;
#Override
public void onCreate() {
// TODO Auto-generated method stub
mHandlers = new ArrayList<Handler>();
Toast.makeText(this, "GetCountDataGangguan.onCreate()",
Toast.LENGTH_SHORT).show();
//getambil_jmlgangguan();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "GetCountDataGangguan.onBind()", Toast.LENGTH_SHORT)
.show();
return messenger.getBinder();
}
public class LocalBinder extends Binder {
public GetCountDataGangguanService getServerInstance() {
return GetCountDataGangguanService.this;
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d("GetCountDataGangguan.onDestroy()", "Sudah di destroy");
Toast.makeText(this, "GetCountDataGangguan.onDestroy()",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "GetCountDataGangguan.onUnbind()",
Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
public String getambil_jmlgangguan(){
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String unit_id = user.get(SessionManager.KEY_UNITID);
String regu_id = user.get(SessionManager.KEY_REGUID);
JSONObject jsondatagangguan = jmlGangguanFUnctions.getcountdata(
regu_id, unit_id);
try {
Log.d("JUMLAH_GANGGUAN",jsondatagangguan.getString(KEY_JUMLAH_DATA));
JUMLAH_GANGGUAN = jsondatagangguan.getString(KEY_JUMLAH_DATA);
} catch (JSONException e) {
e.printStackTrace();
}
return JUMLAH_GANGGUAN;
}
}
How do I call method getambil_jmlgangguan() in another activity e.g MainActivity and get result of JUMLAH_GANGGUAN periodically.
Related
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();
}
}
}
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
}
i am working with Recognizing the User's Current Activity from http://developer.android.com/training/location/activity-recognition.html
i used folow code to create new ActivityRecognitionClient:
public class GPSLocationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener {
private String TAG = "[ServiceDetect]";
//
private ActivityRecognitionClient mActivityRecognitionClient ;
private PendingIntent mPendingIntent ;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (checkGooglePlayAvaible()) {
startTrack();
}
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
// code detetc user acitivity here
getActivityRecognitionClient().requestActivityUpdates((2 * 60 * 1000), createPendingRequest());
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
mActivityRecognitionClient = null;
mPendingIntent.cancel();
mPendingIntent = null;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try{
connectionResult.startResolutionForResult((Activity) this.getApplicationContext(), 0);
} catch (IntentSender.SendIntentException e) {
// it happens if the resolution intent has been canceled,
// or is no longer able to execute the request.e
e.printStackTrace();
}
} else {
// Google Play services has no idea how to fix the issue
// it rarely happens for the location service
}
}
public void startTrack() {
try {
if (!getActivityRecognitionClient().isConnected() || !getActivityRecognitionClient().isConnecting() ) {
Log.v(TAG, "getActivityRecognitionClient is not connected");
getActivityRecognitionClient().connect();
}
}
public PendingIntent createPendingRequest() {
if (null != mPendingIntent) {
} else {
Intent intent = new Intent(getApplicationContext(), ServiceFour.class);
mPendingIntent = PendingIntent.getService(getApplicationContext(), 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return mPendingIntent;
}
/**
* check googleplayservices is avaible or not
*
* #return true if is avaible flase if not
*/
public boolean checkGooglePlayAvaible() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
}
return false;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mIsRemove = false;
}
private ActivityRecognitionClient getActivityRecognitionClient() {
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this);
}
return mActivityRecognitionClient;
}
So with it every 2 min User's Current Activity will be send to service four. in my service four(Intent service) :
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
//
if (result != null) {
//
Log.d("Aha", "he he");
} else {
Log.d("Ohno", "T_T");
}
}
It work fine but when i uninstall app. and install again all ActivityRecognitionResult in servicefour is null it just can be work fine again if i restart device. I don't know how to fix this . Please help me and thanks for reading.
Here is your problem:
E/GooglePlayServicesUtil(18189): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
Your GooglePlayServices are not working.
Make sure you included them properly (post your Gradle files etc).
I will post my code for Recognizing the User's Current Activity but with newest api .
public class GPSLocationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener {
private String TAG = "[ServiceDetect]";
//
private PendingIntent mActivityRecognitionPendingIntent;
// Stores the current instantiation of the activity recognition client
private GoogleApiClient mApiClient;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (checkGooglePlayAvaible()) {
startTrack();
}
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
// -------------------------------------
// to remove ActivityRecognition call
// ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates
//----------------------------
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 2 * 60 * 1000,
createPendingRequest());
//
mApiClient.disconnect();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onConnectionFailed");
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onConnectionSuspended");
mApiClient.connect();
}
public void startTrack() {
if (mApiClient == null) {
mApiClient = new GoogleApiClient.Builder(getApplicationContext()).addApi(ActivityRecognition.API)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
if (!mApiClient.isConnected() || !mApiClient.isConnecting()) {
mApiClient.connect();
}
}
public PendingIntent createPendingRequest() {
if (null != mActivityRecognitionPendingIntent) {
} else {
Intent intent = new Intent(getApplicationContext(), ServiceFour.class);
mActivityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return mActivityRecognitionPendingIntent;
}
public boolean checkGooglePlayAvaible() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
}
return false;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
And now in my servicefour . I receive ActivityRecognitionResult :
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if (ActivityRecognitionResult.hasResult(intent)) {
if (bundle.containsKey("com.google.android.location.internal.EXTRA_ACTIVITY_RESULT")) {
String activityRecognitionResult = bundle
.getParcelable("com.google.android.location.internal.EXTRA_ACTIVITY_RESULT") + "";
Log.d(TAG, "activityRecognitionResult " + activityRecognitionResult +" (^.,,.^)");
}
}
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
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