Android 暂停服务、线程、异步任务?为此使用带有后延迟的处理程序



我有一个后台服务(Service -> Thread -> Timer -> Asynctask )。计时器每 5 秒执行一次异步任务。如果异步任务返回 true,则会发送通知。

现在,我希望服务在我单击通知后等待 20 秒(这意味着在接下来的 20 秒内我没有收到其他通知)。这里需要停止什么"对象"?据我所知,暂停异步任务不是一个好主意。所以要么是服务,要么是线程,对吧?使用后延迟方法的处理程序是最佳解决方案吗?

编辑09.03.2016

public class NotifiyService extends Service {
    String savedsa;
    boolean value;
    protected static final int DEFAULT_TIMEOUT = 5000;
    protected static final int EXTENDED_TIMEOUT = 20000;
    private HandlerThread mBgThread;
    private Handler mBgHandler;
    private MyTimerRunnable mRunnable;

    @Override
    public void onCreate() {
        mBgThread = new HandlerThread("MyBgThread");
        mBgThread.start();
        mBgHandler = new Handler(mBgThread.getLooper(), (Handler.Callback) this);
        mRunnable = new MyTimerRunnable();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SharedPreferences sharedPreferences7 = getSharedPreferences("Prefsa",MODE_WORLD_READABLE);
        savedsa = sharedPreferences7.getString("keysa","");
        Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStarted)+ "n" + savedsa,Toast.LENGTH_LONG).show();
        mBgHandler.removeCallbacks(mRunnable);
        mBgHandler.postDelayed(mRunnable,EXTENDED_TIMEOUT);
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        //super.onDestroy();
        mBgHandler.removeCallbacks(mRunnable);
        mBgThread.quitSafely();
        Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
    }
    private class MyTimerRunnable implements Runnable{

        @Override
        public void run() {
            while(!value){
            try {
                URL url = new URL(savedsa);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("HEAD");
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setReadTimeout(3000);
                httpURLConnection.connect();
                value = true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                value = false;
            } catch (ProtocolException e) {
                e.printStackTrace();
                value = false;
            } catch (IOException e) {
                e.printStackTrace();
                value = false;
            }
            if(value){
                NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
                builder.setSmallIcon(R.drawable.dummy);
                Intent intent = new Intent(NotifiyService.this, Main2Activity.class);
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
                builder.setContentIntent(pendingIntent);
                builder.setLights(Color.YELLOW, 600, 600);
                builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
                builder.setContentTitle(getResources().getString(R.string.newNotify));
                builder.setContentText(getResources().getString(R.string.newNotify2));
                builder.setAutoCancel(true);
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(1, builder.build());
            }
            mBgHandler.postDelayed(this,DEFAULT_TIMEOUT);}
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }
}

如果您已经在Service中生成Thread,则不需要AsyncTask。 您可以使用辅助线程来完成所有工作。 如果要使用 postDelayed()Handler ,请将后台线程设置为HandlerThread,并在Looper启动后创建Handler。 您可以通过postDelayed()重新安排相同的Runnable,如果您的通知需要更改行为,只需取消任何现有Runnable并将另一个设置为在所需时间范围内运行即可。

相关内容

最新更新