在一段时间内禁用广播组(Android)

时间:2016-12-16 07:47:22

标签: android android-radiogroup

我在自定义列表视图中有3个广播组。 我需要从早上9点到下午1点启用第一个广播组,然后在此之后禁用。第二个无线电组将从下午1点到晚上8点启用,并且禁用之后和第三个无线电组从晚上8点到早上8点启用并在之后禁用。我怎样才能实现同样的目标?

BroadCastReceiver.java

public class BackgroundService extends Service {
private static BroadcastReceiver mTickReceiver;

public BackgroundService()
{

}



@Override
public IBinder onBind(Intent arg0)
{
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
public void onCreate()
{
    registerReceiver();
}

@Override
public void onDestroy()
{
    unregisterReceiver(mTickReceiver);
    mTickReceiver = null;
}



private void registerReceiver()
{
    mTickReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)  // this will fire every minute
        {
            String shift = null;
            DateFormat df = new SimpleDateFormat("HH:mm");
            String currentTimeString = df.format(Calendar.getInstance().getTime());
            Log.d("CurrentTime",currentTimeString);
            int currentTime=convertTimeToMinutes(currentTimeString);
            Log.d("CurrentTime1", String.valueOf(currentTime));
            Intent i=new Intent();
            i.setAction("TimeData");

            if(currentTime>=480 && currentTime<780) {
                shift = "Shift1";

            }
           else if(currentTime>=780 && currentTime<1200) {
                shift = "Shift2";


            }
           else if(currentTime>=1200 || currentTime<480) {
                shift = "Shift3";

            }
            Log.d("TAG1",shift);

            intent.putExtra("Shift",shift);

            sendBroadcast(i);


        }
    };
    IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK); // this will broadcast Intent every minute
    registerReceiver(mTickReceiver, filter);
}
private int convertTimeToMinutes(String s) {
    String[] hourMin = s.split(":");
    int hour = Integer.parseInt(hourMin[0]);
    int mins = Integer.parseInt(hourMin[1]);
    int hoursInMins = hour * 60;
    return hoursInMins + mins;
}

}

在Activity onCreate方法中,我将调用BroadcastReceiver,如下所示

    Intent i=new Intent(this, BackgroundService.class);
    startService(i);
    IntentFilter filter = new IntentFilter("TimeData");
    registerReceiver(new MyBroadcastReceiver(),filter);

Activity中的BroadCastReceiver类如下

    class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // GET BROADCAST FROM RECEIVER IN THE BACKGROUND SERVICE CLASS
        Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();

        Log.d("ActionData",intent.getAction());  // this works, it is checked

        if (intent.getAction() == "TimeData") {
            String shiftValue1= intent.getStringExtra("Shift");
            Log.d("shiftValue1",shiftValue1);
        }
    }
}

我得到的错误是

  

致命的例外:主要                                                                       过程:com.rakyow.ehandor,PID:11492                                                                       java.lang.RuntimeException:在com.rakyow.ehandor.HandoverDetailActivity$MyBroadcastReceiver@1acc203e中接收广播Intent {act = TimeData flg = 0x10}时出错                                                                           在android.app.LoadedApk $ ReceiverDispatcher $ Args.run(LoadedApk.java:917)                                                                           在android.os.Handler.handleCallback(Handler.java:815)                                                                           在android.os.Handler.dispatchMessage(Handler.java:104)                                                                           在android.os.Looper.loop(Looper.java:194)                                                                           在android.app.ActivityThread.main(ActivityThread.java:5576)                                                                           at java.lang.reflect.Method.invoke(Native Method)                                                                           在java.lang.reflect.Method.invoke(Method.java:372)                                                                           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:956)                                                                           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)                                                                        引起:java.lang.NullPointerException:println需要一条消息                                                                           在android.util.Log.println_native(本机方法)                                                                           在android.util.Log.d(Log.java:139)                                                                           在com.rakyow.ehandor.HandoverDetailActivity $ MyBroadcastReceiver.onReceive(HandoverDetailActivity.java:290)                                                                           在android.app.LoadedApk $ ReceiverDispatcher $ Args.run(LoadedApk.java:907)                                                                           在android.os.Handler.handleCallback(Handler.java:815)                                                                           在android.os.Handler.dispatchMessage(Handler.java:104)                                                                           在android.os.Looper.loop(Looper.java:194)                                                                           在android.app.ActivityThread.main(ActivityThread.java:5576)                                                                           at java.lang.reflect.Method.invoke(Native Method)                                                                           在java.lang.reflect.Method.invoke(Method.java:372)                                                                           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:956)                                                                           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)

2 个答案:

答案 0 :(得分:2)

对于此类功能,您可以创建计时器服务来检查特定时间段的时间,或者您可以使用警报服务,这将在特定时间触发

答案 1 :(得分:1)

这是你每分钟检查时间的方式:

public class BackgroundService extends Service {
    private static BroadcastReceiver mTickReceiver;

    public BackgroundService()
    {

    }



    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onCreate()
    {
        registerReceiver();
    }

    @Override
    public void onDestroy()
    {
        unregisterReceiver(mTickReceiver);
        mTickReceiver = null;
    }



    private void registerReceiver()
    {
        mTickReceiver = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)  // this will fire every minute
            {
                Log.d("TAG", "TICKS");
                // Check current time using getTimeInMilliSeconds() 
               // if time is in your desired range, send UI an intent that it should change radio buttons 

            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK); // this will broadcast Intent every minute
        registerReceiver(mTickReceiver, filter);
    }

}

How to send info/data from a receiver in a service to MainActivity,在您的案例信息中更新用户界面。

在上面的示例中,我传递了位置数据,您可以在检查完时间范围后传递任何信息。

<强>更新

  • 使用SimpleDateFormat将毫秒转换为小时字符串(例如,1481879288是&#34; 09:08 am&#34;(gmt))。

  • 编写一个将HH:mm [am / pm]格式转换为分钟的函数 - &#34; 09:08 am&#34;进入728分钟,或说&#34; 02:35 pm&#34;到875分钟,这是从凌晨12:00开始,上午12:00是0分钟。 (Hint: break string, convert hours to minutes, add minutes part to converted one, write checks for am/pm) 提示提示 - 如果您将毫秒转换为24小时格式,您将避免检查上午/下午,只需乘以60xhourPart并添加分钟部分。

  • 将分钟范围与您的范围进行比较,例如:从早上08:00到晚上8:00,这将是480分钟到1200分钟,所以如果当前时间是09:08 am,检查将是:

     int currentTime=convertTimeToMinutes(currentTimeString);              
    
     // to check if time is between 08:00am to 08:00pm
    
     if(currentTime>=480 && currentTime<=1200) {
    
        Log.d(TAG,"Current time is in between 08:00am to 08:00pm");
    
    }
    
  

如果范围是在晚上8点到8点之间(第二天发生)??

如果是这种情况,请使用检查以查看时间是否大于晚上8点或低于上午8点,请注意此处检查是否为||不是&amp;&amp;

if (currentTime>=1320 || currentTime <=480)
{
// your stuff
}

更新2

String比较必须始终采用.equals()方法而不是==,因为您使用==,行

String shiftValue1= intent.getStringExtra("Shift")

永远不会执行,你应该把它写成:

if (intent.getAction().equals("TimeData")) {
            String shiftValue1= intent.getStringExtra("Shift");
            Log.d("shiftValue1",shiftValue1);
}

更新3

不要这样做:

intent.putExtra("Shift",shift);

这样做:

i.putExtra("Shift",shift);

看到你发送的是同一个意图对象。