在一天中的特定时间执行任务(代码行)

时间:2013-11-13 06:16:10

标签: android scheduled-tasks data-connections

我正在尝试在一天的特定时间启用/停用移动数据。这就是我到目前为止所做的:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        Calendar objCal = Calendar.getInstance();
    objCal.set(Calendar.HOUR_OF_DAY, 11);
    objCal.set(Calendar.MINUTE, 0);
    objCal.set(Calendar.SECOND, 0);
    //
    // Intent intent = new Intent(this, MainActivity.class);
    // intent.setAction("com.sang.mobiledata.ACTION");
    //
     PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(
     this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
     AlarmManager am = (AlarmManager)
     this.getSystemService(Context.ALARM_SERVICE);
     am.setRepeating(AlarmManager.RTC_WAKEUP, objCal.getTimeInMillis(),
     AlarmManager.INTERVAL_DAY, pi);

基本上,我想在晚上10点关闭数据连接。我知道这将通过以下方式实现:

objNetwork.setMobileDataEnabled(getBaseContext(), false);

并在早上6点再次打开

objNetwork.setMobileDataEnabled(getBaseContext(), true);

我只是不知道如何(以及在​​哪里)给出这个条件。

编辑:

public class Network {

public void setMobileDataEnabled(Context context, boolean enabled) {

    try {
        ConnectivityManager conman = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        Method setMobileDataEnabledMethod = ConnectivityManager.class
                .getDeclaredMethod("setMobileDataEnabled", boolean.class);

        setMobileDataEnabledMethod.setAccessible(true);
        setMobileDataEnabledMethod.invoke(conman, enabled);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

编辑2(完整代码):

ConnBroadCastReceiver.java

public class ConnBroadcastReceiver extends BroadcastReceiver {

private static final String CONN_ACTION = "com.sang.mobiledata.IntentAction.RECEIVE_CONN_UPDATE";
Network objNetwork = new Network();
@Override
public void onReceive(Context context, Intent intent) {
    if(CONN_ACTION.equals(intent.getAction())) {
        boolean enableConn = intent.getBooleanExtra("FLAG_KEY", false);
        objNetwork.setMobileDataEnabled(context, enableConn);
    }
 }

}

MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    triggerEnable(true, 6);
    triggerEnable(false, 22);
}

private void triggerEnable(boolean enableData, int hourInDay) {
    Calendar calendar = Calendar.getInstance();
    if (enableData) {
        calendar.set(Calendar.HOUR_OF_DAY, hourInDay);
    } else {
        calendar.set(Calendar.HOUR_OF_DAY, hourInDay);
    }
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    Intent broadcastIntent = new Intent("com.sang.mobiledata.IntentAction.RECEIVE_CONN_UPDATE");
    broadcastIntent.putExtra("FLAG_KEY", enableData);
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, broadcastIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);
}

Network.java

 public class Network {

public void setMobileDataEnabled(Context context, boolean enabled) {

    try {
        ConnectivityManager conman = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        Method setMobileDataEnabledMethod = ConnectivityManager.class
                .getDeclaredMethod("setMobileDataEnabled", boolean.class);

        setMobileDataEnabledMethod.setAccessible(true);
          setMobileDataEnabledMethod.invoke(conman, enabled);
    } catch (Exception e) {
        e.printStackTrace();
     }

}

的manifest.xml

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <receiver
        android:name="com.sang.mobiledata.ConnBroadcastReceiver"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.sang.mobiledata.IntentAction.RECEIVE_CONN_UPDATE" />
        </intent-filter>
    </receiver>

2 个答案:

答案 0 :(得分:2)

我从来没有尝试过切换数据连接 - 假设上面提供了适当的权限(如果有的话),并且上面的代码没有使用反射,因为我看到其他人正在拍摄自己脚...

但是,如果您打算在特定时间打开应用程序活动,那么至少从用户体验的角度来看,我会说这是一种不好的做法。您可以通过PendingIntent.getBroadcast(...)发送广播消息,而不是这样做。

话虽如此:

  1. 使用您自己的操作构造一个intent,在其中添加一个有意义的布尔标志(true表示启用连接,否则为false)。
  2. 将该意图传递给您的PendingIntent.getBroadcast
  3. 在班级中创建BroadcastReceiver,在Manifest中注册并正确处理该操作。像:
  4. BroadcastReceiver类:

    public class ConnBroadcastReceiver extends BroadcastReceiver {
        private static final String CONN_ACTION = "my_package_name.IntentAction.RECEIVE_CONN_UPDATE";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if(CONN_ACTION.equals(intent.getAction())) {
                boolean enableConn = intent.getBooleanExtra("FLAG_KEY", false);
                objNetwork.setMobileDataEnabled(context, enableConn);
            }
        }
    }
    

    在Manifest中注册:

    <receiver
        android:name="my_package_name.ConnBroadcastReceiver"
        android:exported="false" >
            <intent-filter>
                <action android:name="my_package_name.IntentAction.RECEIVE_CONN_UPDATE" />
            </intent-filter>
    </receiver>
    

    并从上面的代码中触发广播:

    Intent broadcastIntent = new Intent("my_package_name.IntentAction.RECEIVE_CONN_UPDATE");
    broadcastIntent.putExtra("FLAG_KEY", enableData);
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, objCal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
    

    编辑以上onCreate可以重写为:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        triggerEnable(true, 6);
        triggerEnable(false, 22);
    }
    
    private void triggerEnable(boolean enableData, int hourInDay) {
        Calendar calendar = Calendar.getInstance();
        if (enableData) {
            calendar.set(Calendar.HOUR_OF_DAY, hourInDay);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, hourInDay);
        }
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Intent broadcastIntent = new Intent("my_package_name.IntentAction.RECEIVE_CONN_UPDATE");
        broadcastIntent.putExtra("FLAG_KEY", enableData);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, broadcastIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pi);
    }
    

答案 1 :(得分:0)

您可以设置两个警报,一个用于晚上10点,另一个用于早上6点,然后当警报触发时,系统将为您启动服务以进行自己的工作。

   PendingIntent pi = PendingIntent.getService(this, 0, new Intent(
     this, YourOwnerService.class), PendingIntent.FLAG_UPDATE_CURRENT);