可以通过Button更新服务的活动

时间:2012-08-13 14:44:09

标签: android service android-activity

我正在尝试从活动更新服务。当用户单击按钮时,活动将数据保存到手机上的sql lite数据库。我想在这里做的是,当单击此按钮时,服务将刷新并使用新数据。

我在按钮上使用了启动/停止服务,但应用程序崩溃并跳过不同的活动。

我认为我的问题类似于Android: Update / Refresh a running serviceBroadcast Receiver within a Service

但是,我没有更新小部件或其他Android原生组件。该服务是一个自定义类。

请注意,广播接收器在手机启动时启动此服务。 此外,Logcat窗口不会滚动读数。它上下颠簸。所以我没有错误日志给你看。

如何创建一个允许服务在用户点击活动按钮时更新的功能?

这是我的活动(按钮位于底部):

        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);


                }
            });
    }

    }

以下是我想要更新的服务:

    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 ...");

        }



    }

}

0 个答案:

没有答案