1

アクティビティからサービスを更新しようとしています。ユーザーがボタンをクリックすると、Activity は電話の sql lite データベースにデータを保存します。ここでやりたいことは、このボタンをクリックすると、サービスが更新され、新しいデータが使用されることです。

ボタンで start/stopservice を使用していましたが、アプリがクラッシュして別のアクティビティにスキップします。

私の質問は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;
    }

}

ブロードキャスト レシーバー:

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

        }



    }

}
4

0 に答える 0