如何使用动态间隔调用服务

时间:2013-11-08 10:34:51

标签: android service alarmmanager

您好我的应用程序我通过使用后台服务和报警管理器以动态间隔执行webview .Webview将以指定的时间间隔打开。如果启动服务后用户可以更改间隔时间(这是第一次时间间隔不同)这里我想要将此时间间隔更新为警报管理器。

在这里,我正在尝试

private void loadWebview() {
    try {
        loadPrefValues();

        Calendar cur_cal = Calendar.getInstance();
        cur_cal.setTimeInMillis(System.currentTimeMillis());
        Intent webViewIntent = new Intent(MyService.this, XorWebView.class);
        webViewIntent.putExtra("url", mStr);
        webViewIntent.putExtra("duration", mDurationStr);
        webViewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pintent = PendingIntent.getActivity(MyService.this, 0,
                webViewIntent, 0);

        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (mIntervalStr.equals("1 minute")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 1 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("2 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 2 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("5 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 5 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("10 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 10 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("30 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 30 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("60 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 60 * 60 * 1000, pintent);
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    System.out.println("Service.onStart()" + "Url:" + mStr
            + "Send to WebActivity");
}

此方法仅在第一次指定的时间间隔执行。我的代码出错了什么?

编辑#1

在MainActivity中,我使用开/关切换按钮和列表视图的间隔。在列表视图中我放1,5,10,20,30,60分钟。用户可以在列表视图中选择任何间隔,当切换isChecked()时我在这里开始服务。

在此服务类中,我使用Alarmmanager调用间隔。

当用户在主要活动中更改间隔将在警报管理器中更新时,我想要的确切。

我的服务类

public class MyService extends Service {

BroadcastReceiver mReceiver = null;
String mStr, mIntervalStr, mDurationStr;
PendingIntent pintent;
AlarmManager alarm;

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

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    Toast.makeText(MyService.this, "Service Created", Toast.LENGTH_SHORT)
            .show();
    System.out.println("Service.onCreate()");

}

@Override
@Deprecated
public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);

    Toast.makeText(MyService.this, "Service started", Toast.LENGTH_SHORT)
            .show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    // Let it continue running until it is stopped.
    try {
        loadWebview();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    Toast.makeText(MyService.this, "Service command started",
            Toast.LENGTH_SHORT).show();
    return START_STICKY;
}


private void loadWebview() {
    try {
        loadPrefValues();

        Calendar cur_cal = Calendar.getInstance();
        cur_cal.setTimeInMillis(System.currentTimeMillis());
        Intent webViewIntent = new Intent(MyService.this, XorWebView.class);
        webViewIntent.putExtra("url", mStr);
        webViewIntent.putExtra("duration", mDurationStr);
        webViewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pintent = PendingIntent.getActivity(MyService.this, 0,
                webViewIntent, 0);

        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pintent);
        if (mIntervalStr.equals("1 minute")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,cur_cal.getTimeInMillis(),
                    1 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("2 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 2 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("5 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 5 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("10 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 10 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("30 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 30 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("60 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 60 * 60 * 1000, pintent);
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    System.out.println("Service.onStart()" + "Url:" + mStr
            + "Send to WebActivity");
}

private void loadPrefValues() {
    SharedPrefManager.Init(MyService.this);
    SharedPrefManager.LoadFromPref();
    String s1 = SharedPrefManager.getsUrl().toString();
    String s2 = SharedPrefManager.getsInterval().toString();
    String s3 = SharedPrefManager.getsDuration().toString();

    mStr = s1;
    mIntervalStr = s2;
    mDurationStr = s3;


}


@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if (mReceiver != null)
        unregisterReceiver(mReceiver);
    alarm.cancel(pintent);
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    System.out.println("Service.onDestroy()");
}

}

2 个答案:

答案 0 :(得分:0)

您应首先取消之前的pendingIntent,然后设置new。

在此行之后的代码中。

alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarm.cancel(pintent);

答案 1 :(得分:0)

事情正在发生。

- >从您的活动中更新alarmManager。 - >将当前时间间隔保存在首选项中以供将来使用。 - >实现重启广播接收器,当设备重启时,它将被调用。 - >在重启功能中设置alarmManager。使用首选项中保存的时间间隔。

将此代码复制到您的活动中。

       listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View v, int position,
                            long id) {
                        loadWebView(user's new selected minutes);
                    }
});

以下是设置AlarmManager的代码

     private void loadWebview(String minutes) {
    try {
        loadPrefValues();



        saveCurrentTimeInterval(minutes);




        Calendar cur_cal = Calendar.getInstance();
        cur_cal.setTimeInMillis(System.currentTimeMillis());
        Intent webViewIntent = new Intent(MyService.this, XorWebView.class);
        webViewIntent.putExtra("url", mStr);
        webViewIntent.putExtra("duration", mDurationStr);
        webViewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pintent = PendingIntent.getActivity(MyService.this, 0,
                webViewIntent, 0);

        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (minutes.equals("1 minute")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 1 * 60 * 1000, pintent);
        }
        if (minutes.equals("2 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 2 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("5 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 5 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("10 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 10 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("30 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 30 * 60 * 1000, pintent);
        }
        if (mIntervalStr.equals("60 minutes")) {
            alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                    cur_cal.getTimeInMillis(), 60 * 60 * 1000, pintent);
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

}

private void saveCurrentTimeInterval(String minute) { SharedPreferences pref = getSharedPreferences(“time”,Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); eidtor.putString(“interval”,minute); editor.commit(); }

现在是ReBoot监听器

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

public class BootCompleteReceiver extends BroadcastReceiver {   

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

        SharedPreferences pref = context.getSharedPreferences("time", Context.MODE_PRIVATE);
        setAlarmManager(pref.getString("interval", ""));   

    }  

    private void setAlarmManager(String minutes) {
        try {
            loadPrefValues();

            Calendar cur_cal = Calendar.getInstance();
            cur_cal.setTimeInMillis(System.currentTimeMillis());
            Intent webViewIntent = new Intent(MyService.this, XorWebView.class);
            webViewIntent.putExtra("url", mStr);
            webViewIntent.putExtra("duration", mDurationStr);
            webViewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            pintent = PendingIntent.getActivity(MyService.this, 0,
                    webViewIntent, 0);

            alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            if (minutes.equals("1 minute")) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cur_cal.getTimeInMillis(), 1 * 60 * 1000, pintent);
            }
            if (minutes.equals("2 minutes")) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cur_cal.getTimeInMillis(), 2 * 60 * 1000, pintent);
            }
            if (mIntervalStr.equals("5 minutes")) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cur_cal.getTimeInMillis(), 5 * 60 * 1000, pintent);
            }
            if (mIntervalStr.equals("10 minutes")) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cur_cal.getTimeInMillis(), 10 * 60 * 1000, pintent);
            }
            if (mIntervalStr.equals("30 minutes")) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cur_cal.getTimeInMillis(), 30 * 60 * 1000, pintent);
            }
            if (mIntervalStr.equals("60 minutes")) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP,
                        cur_cal.getTimeInMillis(), 60 * 60 * 1000, pintent);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

}

在你xml。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootCompleteReceiver">  
            <intent-filter>     
                <action android:name="android.intent.action.BOOT_COMPLETED"/>  
                <category android:name="android.intent.category.DEFAULT" />  
            </intent-filter>  
        </receiver>