使用alarmManager和服务从服务器获取数据反复 [英] Use alarmManager and service to get data from server repeatedly

查看:259
本文介绍了使用alarmManager和服务从服务器获取数据反复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是要验证每两个小时才得知有在数据库中的新数据,我创建这个用户界面:

My question is I want to verify every two hour that there is new data in the database, for that I create this user interface :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

        <EditText
            android:id="@+id/speedAlert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:gravity="center"
            android:hint="km/h"
            android:inputType="number" />

        <CheckBox
            android:id="@+id/checkBoxSpeed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnConfirmSpeed"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Confirm" />

因此​​,当用户输入的EditText的值,并选中复选框,并单击按钮,创建一个报警,并每两小时,在该报警器启动服务确认:

so when user enter the value of the edittext and check the checkbox and confirm by clicking the button, an alarm is created and every two hour this alarm start a service :

btnConfirmSpeed.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            cal = Calendar.getInstance();
            triggerAtTime = cal.getTimeInMillis()+ (1 * 30 * 60 * 1000); // starts in 30 minutes
            repeat_alarm_every = (2 * 60 * 60 * 1000); // repeat every 2 hour
            int _id = (int) System.currentTimeMillis();
            Intent intent = new Intent(Alarm.this, NotificaSpeed.class);
            //get the value of checkbox from sharedpreferences
                    boolean tgpref = pref.getBoolean("checkVitessePref", false); 
            String sp = speedAlert.getText().toString();
            if(checkBoxSpeed.isChecked()){
                if(sp.matches(""))
                    Toast.makeText(getApplicationContext(), "specify speed", Toast.LENGTH_SHORT).show();
                else 
                {
                    editor = pref.edit();
                    editor.putBoolean("checkVitessePref", true); // value to store
                    editor.putInt("speedalarm", Integer.parseInt(speedAlert.getText().toString()));
                    editor.commit();

                    pintent = PendingIntent.getService(Alarm.this, _id, intent, 0);
                    alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                    alarm.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, repeat_alarm_every, pintent);


                } 
            }else {

                alarm.cancel(pintent);
                editor.putBoolean("checkVitessePref", false); // value to store
                editor.commit();
                stopService(new Intent(Alarm.this,NotificaSpeed.class));
            }

        }
    });

在NotificaSpeed​​是服务:

the NotificaSpeed is the service :

public class NotificaSpeed extends Service{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public void onCreate() {

    mNotificationManager = (NotificationManager) getSystemService(ns);
    super.onCreate();
}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    new VerifySpeedCar().execute();
    return super.onStartCommand(intent, flags, startId);
}

public void notification(int carsNumber, int speed){
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(NotificaSpeed.this);
    if(carsNumber != 0)

        notificationBuilder.setContentTitle(carsNumber+" cars are exceeding the speed");

                        .setSmallIcon(R.drawable.ic_launcher)
                        .setAutoCancel(true);
    final int _idI = (int) System.currentTimeMillis();
    Intent notificationIntent = new Intent(NotificaSpeed.this, ListCars.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, _idI, notificationIntent, 0);
    notificationBuilder.setContentIntent(contentIntent);

    notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

    mNotificationManager.notify(SIMPLE_NOTIFICATION_ID, notificationBuilder.build());

}

class VerifySpeedCar extends AsyncTask<String, String, String> {

protected String doInBackground(String... args) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(TAG_ACCOUNTID, accountID));
    params.add(new BasicNameValuePair(TAG_SPEEDKPH, ""+speedpref)); // how can I get the value of edittext of the speed from the sharedpreferences?

        JSONObject json = jParser.makeHttpRequest(url, "GET", params);
        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                cars = json.getJSONArray(TAG_CARS);
                carsNumber = cars.length();
            } else 
                carsNumber = 0;

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return null;
}
protected void onPostExecute(String file_url) {
  if( carsNumber != 0){
      notification(carsNumber, speedpref);
  }
}}}

第一个是很好的方式做验证或我做错了?
第二个我怎么能得到的EditText从共享preferences的价值?
最后当我关闭应用程序的服务太采空,所以当我再次启动应用程序服务是没有更多的运行,但复选框的值仍然选中,我如何解决此问题?

first is that good way to do the verification or I am doing it wrong? second how can I get the value of the edittext from the sharedpreferences? finally when I close the app the service is stoped too, so when I start the app again the service is no more running but the value of checkbox is still checked, How can I resolve this?

感谢您百忙之中阅读我的问题的时间。任何帮助将AP preciated

thank you for taking the time to read my question. any help will be appreciated

推荐答案

如何从共享preference得到的EditText的价值?

创建共享preference和共享preference.Editor对象。

Create SharedPreference and SharedPreference.Editor objects.

 SharedPreferences sp ;
 sp = this.getSharedPreferences("YOUR PREF NAME", 0);

我相信你都可以从在的EditText字符串str值如

I believe you are getting the value from edittext in String str like

str = ed.getText().toString();
SharedPreferences.Editor editor = sp.edit();
editor.putString("edit_text", str);
editor.commit();

从共享preference检索的EditText值

如果您检索在同一个活动,然后

If you're retrieving in the same activity then

String value = sp.getString("edit_text", null);

如果在不同的活动则先实例共享preference这样

If in different activity then first instantiate the SharedPreference like this

SharedPreference sp = this.getSharedPreferences("YOUR PREF NAME", 0);

这篇关于使用alarmManager和服务从服务器获取数据反复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆