如果新线程在30秒内运行,则android停止旧线程

时间:2016-08-10 08:13:31

标签: java android multithreading

我有一个广播接收器,我有一个线程在运行,30秒后它将布尔值更改为true。它运行正常,但问题是,如果在30秒之前再次调用broadcastreceiver,则旧线程在30秒之前将布尔值设置为true。我希望在调用broadcastreceiver之后30秒,布尔值为true。但是如果接收器运行并且在30秒之前它再次运行,那么布尔值在我想要之前变为true。 这是代码

public class ConectivityChangeBroadcast extends BroadcastReceiver {

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


        ListDataTemp.connectivitychanged = false;
        //SettingsActivity.wifiget(context);

        Thread t = new Thread(){
            public void run(){

                try {
                    Thread.sleep(30000);
                    ListDataTemp.connectivitychanged = true;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        t.interrupt();

    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用Handler实例执行此操作:

public class ConectivityChangeBroadcast extends BroadcastReceiver {

    private Handler mHandler;

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

        if (mHandler == null)
             mHandler = new Handler();
        else
             mHandler.removeCallbacksAndMessages(null); // cancel previous calls

        ListDataTemp.connectivitychanged = false; 
        //SettingsActivity.wifiget(context); 

        Runnable t = new Runnable(){
            public void run(){ 
                ListDataTemp.connectivitychanged = true;
            } 
        }; 
        mHandler.postDelayed(t, 30000);

    } 
} 

答案 1 :(得分:0)

您可以利用时间和共享偏好。

public class ConectivityChangeBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            Long lastTimeRun=getLastThreadInfo(context);
            if(lastTimeRun>0 && (System.currentTimeMillis()-lastTimeRun) >30000){
                ListDataTemp.connectivitychanged = true;
            }
            storeLastThreadRunInfo(System.currentTimeMillis());
        }
    }

    private void storeLastThreadRunInfo(Long time) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putLong("time", time);
        editor.apply();
    }

    private Long getLastThreadInfo(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("test", Context.MODE_PRIVATE);
        return prefs.getLong("time", 0L);
    }