如何设置活动是积极的所有时间? [英] How to set activity to be active all the time?

查看:124
本文介绍了如何设置活动是积极的所有时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要激活所有的时间活动。我有哪个线程睡10秒,并从数据库中获取监测值,比较它们并启动方法。我想知道,如果用户返回到其他应用程序和活动,我的活动和线程仍在工作,或者他们是由活动管理器处理并进入暂停,停止破坏?如何保持他们活?
谢谢。
这里是code为螺纹:

 新主题(新的Runnable(){        公共无效的run(){
            // TODO自动生成方法存根
            而(真){
                尝试{
                    视频下载(10000);
                    myHendler.post(新的Runnable(){                        公共无效的run(){
                            // TODO自动生成方法存根                            最后的日历CAL = Calendar.getInstance();
                            INT godina2 = cal.get(Calendar.YEAR);
                            INT mesec2 = cal.get(的Calendar.MONTH);
                            INT dan2 = cal.get(Calendar.DAY_OF_MONTH);
                            INT sati2 = cal.get(Calendar.HOUR_OF_DAY);
                            INT minuti2 = cal.get(Calendar.MINUTE);                            trenutniDatum =新的StringBuilder()追加(dan2).append( - )附加(mesec2 +1).append( - )附加(godina2)。;
                            trenutnoVreme = prepraviVreme(sati2)+:+ prepraviVreme(minuti2);
                            的for(int i = 0; I< primljenoIzBazeDatum.length;我++){
                                串bazaBroj =;
                                串bazaText =;
                                如果(primljenoIzBazeDatum [I]的ToString()等于(trenutniDatum.toString())及。&放大器; primljenoIzBazeVreme [I]的ToString()等于(trenutnoVreme)){                                        INT bazaId =的Integer.parseInt(primljenoIzBazeId [I]);
                                        bazaBroj = primljenoIzBazeBroj [I]的ToString();
                                        bazaText = primljenoIzBazeText [I]的ToString();
                                        串datumPromena =*+ primljenoIzBazeDatum [I]的ToString()+* SENT *;                                        datumVreme.open();
                                        datumVreme.updateData(bazaId,datumPromena);
                                        datumVreme.close();                                        sendPoruka(bazaBroj,bazaText);                                }                            } //结束了
                        } //运行结束
                    });
                }赶上(InterruptedException的E){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
            }
        }
    })。开始();


解决方案

根据我对你想做的事的了解,这里是我会做什么:

首先,创建一个BroadcastReceiver

 公共类轮询扩展广播接收器{
    私人最终字符串标记=轮询;
    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
    Log.i(TAG,轮询broadcastintent收到);
    意图myIntent =新意图(背景下,PollerService.class);
    context.startService(myIntent);
}

然后,创建名为该服务,然后自行关闭

 公共类PollerService延伸服务{
    最后的字符串标记=PollerService;
    @覆盖
    公共无效调用onStart(意向意图,诠释startId){
    Log.i(TAG,服务调用onStart());
    pollingTask.execute();
}AsyncTask的<太虚,太虚,太虚> pollingTask =新的AsyncTask<太虚,太虚,太虚>(){
    @覆盖
    保护无效doInBackground(无效...参数){
        //做你想做的背景
    }    @覆盖
    保护无效onPostExecute(虚空结果){
        stopSelf();
    }
};
}

然后,设置一个AlarmManager唤醒服务,每分钟

  AlarmManager AM =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
意图alarmIntent =新意图(CHECK_DATABASE);
的PendingIntent圆周率= PendingIntent.getBroadcast(上下文,0,alarmIntent,0);
整型= AlarmManager.ELAPSED_REALTIME_WAKEUP;
长间隔= POLLING_INTERVAL_IN_MILLISECONDS;
长triggerTime = SystemClock.elapsedRealtime()+区间;
//对于短的时间间隔setInexact重复是相同exactRepeating,使用至少十五分钟,使之更有效地
am.setInexactRepeating(类型,triggerTime,间隔,PI);
Log.i(TAG,通过设置不精确AlarmManager报警);
}

设置接收器在Android清单

 <接收机器人:名字=轮询>
    &所述;意图滤光器>
        <作用机器人:名字=CHECK_DATABASE/>
    &所述; /意图滤光器>
< /接收器>

最后,一旦收到您的短信所需的取消设置为AlarmManager轮询停止

  AlarmManager AM =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
意向意图=新意图(CHECK_DATABASE);
的PendingIntent圆周率= PendingIntent.getBroadcast(上下文,0,意图,0);
am.cancel(PI);

我认为彼得是正确的,虽然这会杀了你的电池,除非你将只检查,直到你获得所需的信息,然后不轮询,这是一个很短的时间。

此外,如果当你想从你刚设置的AlarmManger醒来,当时该服务的数据库中的一个电话发送短信,就可以得到准确的时间执行的操作,并用它做。这将是最好的方法(我不能完全做出来,如果​​这是从你们的情况下code,但它似乎是从你的评论)。

I have activity which needs to be active all the time. I have thread which sleep 10 sec, and monitors values taken from database, compare them and start method. I'm wondering if user go back to other applications and activities, does my activity and thread still work, or they are handled by activity manager and go to pause-stop-destroy?? How to stay them a live?? Thank you. here is code for that thread:

 new Thread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            while(true){
                try {
                    Thread.sleep(10000);
                    myHendler.post(new Runnable() {

                        public void run() {
                            // TODO Auto-generated method stub

                            final Calendar cal = Calendar.getInstance();
                            int godina2 = cal.get(Calendar.YEAR);
                            int mesec2 = cal.get(Calendar.MONTH);
                            int dan2 = cal.get(Calendar.DAY_OF_MONTH);
                            int sati2 = cal.get(Calendar.HOUR_OF_DAY);
                            int minuti2 = cal.get(Calendar.MINUTE);

                            trenutniDatum = new StringBuilder().append(dan2).append("-").append(mesec2 +1).append("-").append(godina2);
                            trenutnoVreme = prepraviVreme(sati2) + ":" + prepraviVreme(minuti2);
                            for(int i = 0; i < primljenoIzBazeDatum.length; i++){
                                String bazaBroj = "";
                                String bazaText = "";
                                if(primljenoIzBazeDatum[i].toString().equals(trenutniDatum.toString()) && primljenoIzBazeVreme[i].toString().equals(trenutnoVreme)){

                                        int bazaId = Integer.parseInt(primljenoIzBazeId[i]);
                                        bazaBroj = primljenoIzBazeBroj[i].toString();
                                        bazaText = primljenoIzBazeText[i].toString();
                                        String datumPromena = "*" + primljenoIzBazeDatum[i].toString() + "* SENT *";

                                        datumVreme.open();
                                        datumVreme.updateData(bazaId, datumPromena);
                                        datumVreme.close();

                                        sendPoruka(bazaBroj, bazaText);

                                }

                            } // end for


                        } // end run
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }).start();

解决方案

Based on my understanding of what you want to do, here is what I would do :

First, create a BroadcastReceiver

public class Poller extends BroadcastReceiver {
    private final String TAG = "Poller";
    @Override
    public void onReceive( Context context, Intent intent ) {
    Log.i(TAG, "Poller broadcastintent received");
    Intent myIntent = new Intent( context, PollerService.class );
    context.startService( myIntent );
}

then , create the service that is called and then shuts itself down

public class PollerService extends Service {
    final String TAG = "PollerService";
    @Override
    public void onStart(Intent intent, int startId) {
    Log.i(TAG, "Service onStart()");
    pollingTask.execute();
}

AsyncTask<Void, Void, Void> pollingTask = new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... param) {
        // Do what you want in the background
    }

    @Override
    protected void onPostExecute(Void result) {
        stopSelf();
    }
};
}

then, set an AlarmManager to wake the service every minute

AlarmManager am = ( AlarmManager ) getSystemService( Context.ALARM_SERVICE );
Intent alarmIntent = new Intent( "CHECK_DATABASE" );
PendingIntent pi = PendingIntent.getBroadcast(context, 0 , alarmIntent, 0 );
int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long interval = POLLING_INTERVAL_IN_MILLISECONDS;
long triggerTime = SystemClock.elapsedRealtime() + interval;
// For short intervals setInexact repeating is same as exactRepeating, use at least fifteen minutes to make it more efficient
am.setInexactRepeating( type, triggerTime, interval, pi );
Log.i(TAG, "Set inexact alarm through AlarmManager");
}

setup the receiver in Android manifest

<receiver android:name="Poller">
    <intent-filter>
        <action android:name="CHECK_DATABASE"/>
    </intent-filter>
</receiver>

finally, unset the AlarmManager to stop polling once your required SMS is received

AlarmManager am = ( AlarmManager ) getSystemService( Context.ALARM_SERVICE );
Intent intent = new Intent( "CHECK_DATABASE" );
PendingIntent pi = PendingIntent.getBroadcast( context, 0 , intent, 0 );
am.cancel(pi);

I do think that Peter is right though and this will kill you battery unless you'll only be checking until you get the required info and then don't poll and that's a short time.

Also, if you can get the exact time when you want to send the SMS with a single call from the database you can just set up the AlarmManger to wake up the service at that time, perform the action and be done with it. That would be the best approach (I can't quite make out if that is the case from you code but it does seems to be from you comments).

这篇关于如何设置活动是积极的所有时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆