1

I am trying to update a service from an activity. The Activity saves data to the sql lite database on the phone when the user clicks on a button. What I would like to do here, is when this button is clicked, the service is refreshed and uses the new data.

I was using start/stopservice on the button, but the app crashes and skips around to different activities.

I thought my question was similar to Android: Update / Refresh a running service and Broadcast Receiver within a Service

However, I'm not updating a widget or another android native component. The service is a custom class.

Please note that a Broadcast receiver starts this service on Boot of the phone. Also, Logcat window dosen't scroll the readouts. It jerks up and down. So I don't have an error log to show you.

How do I create a function that would allow the service to update when the user clicks on the button in an activity?

Here is my activity (button is at the bottom):

        import java.sql.Timestamp;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;

    import org.joda.time.DateTime;

    import android.app.Activity;
    import android.app.ActivityManager;
    import android.app.ActivityManager.RunningServiceInfo;
    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.ToggleButton;

    import com.google.android.gcm.demo.app.R;
    import com.google.android.gcm.demo.app.EventList.DataView;
    import com.google.android.gcm.demo.app.EventList.EventDetails;
    import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;

    public class AlertDetails extends Activity {

        Integer id;
        String name;
        String date;
        String startTime;
        String endTime;
        String location;
        int alertState;
        Bundle bundle;
        String alertTime;
        String s;
        private TextView mTitleDisplay;
        private TextView mDateDisplay;
        private TextView mTimeDisplay;
        private TextView mTimeEndDisplay;
        private TextView mLocationDisplay;
        private TextView mAlertDisplay;
        private String update_alarmTime;
        String eventYear;
        String eventDay;
        String eventMonth;
        String eventdate;
        Context context;
        Intent  alarmServiceControl;

        DatabaseSqlite entry = new DatabaseSqlite(AlertDetails.this);

    //  Intent startServiceIntent = new Intent(context, AlarmsService.class);



        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.alertview);

            bundle = getIntent().getExtras();
            id = bundle.getInt("id");
            name = bundle.getString("eventName");
            date = bundle.getString("date");
            startTime = bundle.getString("startTime");
            endTime = bundle.getString("endTime");
            location = bundle.getString("location");
            alertState = bundle.getInt("alertState");
            alertTime = bundle.getString("alertTime");
            alertTime = "10:00:00";// need to be hooked up correctly to get the right 

            // capture our View elements
            mTitleDisplay = (TextView) findViewById(R.id.titleDisplay);
            mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
            mTimeEndDisplay = (TextView) findViewById(R.id.timeEndDisplay);
            mLocationDisplay = (TextView) findViewById(R.id.locationDisplay);
            mAlertDisplay = (TextView) findViewById(R.id.alertDisplay);

            // set start
            mTimeDisplay.setText(startTime);
            mTimeEndDisplay.setText(endTime);

            // set title
            mTitleDisplay.setText(name);

            // set Date
            eventYear = date.substring(0, 4);
            eventDay = date.substring(5, 7);
            eventMonth = date.substring(8, 10);
            mDateDisplay.setText(eventDay + "-" + eventMonth + "-" + eventYear);

             eventdate = eventDay + "/" + eventMonth + "/" + eventYear;

            // set location
            mLocationDisplay.setText(location);


            if (alertState == 0) {
                entry.open();
                mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
                entry.close();
            }
            if (alertState == 1) {

                mAlertDisplay.setText("Alert is OFF");
            }



            Button button1 = (Button) findViewById(R.id.btnSetAlert);

            button1.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    if (alertState == 0) {
                        alertState++;
                        mAlertDisplay.setText("Alert is OFF");
                        entry.open();
                        entry.updateAlertState(id, alertState);
                        entry.close();


                    } else {

                        //turn alarm on
                        entry.open();
                        mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
                        alertState = 0;
                        entry.updateAlertState(id, alertState);
                        entry.close();


                    }
                    // TODO check if service is running
                    stopService(new Intent(AlertDetails.this,
                            AlarmsService.class));
                    startService(new Intent(AlertDetails.this,
                            AlarmsService.class));

                    Intent intent = new Intent(AlertDetails.this,
                            AlertView.class);
                    startActivity(intent);


                }
            });
    }

    }

Here is the service I'd like to update:

    package com.google.android.gcm.demo.app.Alerts;

import java.util.Calendar;
import java.util.List;

import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class AlarmsService extends Service {

    DatabaseSqlite db = new DatabaseSqlite(this);
    List<Alerts> listAlerts;
    PendingIntent pendingIntent;

    String tag = "alerttService";

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Created from Alerts service ...",
                Toast.LENGTH_LONG).show();
        Log.i(tag, "Service created...");
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "started onstart command Created from Alerts service .");
        return super.onStartCommand(intent, flags, startId);// START_STICKY;
    }

    @Override
    public void onStart(final Intent intent, int startId) {
        super.onStart(intent, startId);

        Toast.makeText(this, "Created from Alerts service started...",
                Toast.LENGTH_LONG).show();
        Log.i(tag, "Service started. ..");

        // for looops


        Thread thread = new Thread() {
            @Override
            public void run() {

                Boolean x = true;
                while (x) {

                    db.open();
                    listAlerts = db.getAlarmsForService();
                    db.close();
                    int alerts=listAlerts.size();
                    for (int i = 0; i < alerts; i++) {
                        Alerts item = listAlerts.get(i);
                        item.getRowId();
                        item.getRemoteServerId();
                    String alertInMills = item.getAlertDateInMills();
                    String alertDuration = item.getAlertDurationInMinutes();
                    String eventName = item.getEventName();
//                      intent.putExtra("eventState", item.getEventState());
//                      intent.putExtra("startTime", item.getStartTime());
//                      intent.putExtra("alertState", item.getAlertState());
//                      intent.putExtra("eventName", item.getEventName());
//                      intent.putExtra("location", item.getLocation());
//                      intent.putExtra("alertTime", item.getAlertTime());

//                      intent.putExtra("date", item.getDate());


                    long longAlertInMills = Long.parseLong(alertInMills);



                     pendingIntent = PendingIntent.getService(AlarmsService.this, 0,intent, 0);

                     AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                     Calendar calendar = Calendar.getInstance();

                    // go to data base for time in mills

                     calendar.setTimeInMillis(longAlertInMills);

                     alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                     pendingIntent);
                    //
                     System.out.println(calendar.toString());

                    }

                    //
                    System.out.println("thread");
                    x = false;

                }

            }
        };

        thread.start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

BroadCast Receiver:

package com.google.android.gcm.demo.app.Alerts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmsBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "BootReceiver";

    Intent startServiceIntent;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {

            startServiceIntent = new Intent(context, AlarmsService.class);
            context.startService(startServiceIntent);
            Log.d("TAG", "alarmBroadcastReceiver");

            System.out.println("alarm broadcast ...");

        }



    }

}
Community
  • 1
  • 1
Leoa
  • 1,167
  • 2
  • 14
  • 31
  • 1
    Using content observers would be better. Let the service create a content observer to listen to the database changes. – Gautham Aug 13 '12 at 14:48

0 Answers0