Android计时器在后台服务崩溃的应用程序

时间:2015-12-05 07:25:17

标签: java android service handler

您好我正在使用android。我的应用程序中有后台服务。我希望使用服务中的计时器在后台的时间间隔内执行一个函数。当我使用handler.post方法时,它会导致我的应用程序在某些设备中崩溃。但它在moto G中工作正常。 这是我的服务类

public class SyncService extends Service{

    Timer timer;
    Handler handler ;
    SyncData sync_data;
    TimerTask timerTask;
    PrefManager pref;
    DbHelper db;
    ConnectionDetector cd;

    public SyncService() {


    }

    @Override

    public IBinder onBind(Intent intent) {

        throw new UnsupportedOperationException("Not yet implemented");

    }

    @Override

    public void onCreate() {

        pref= new PrefManager(SyncService.this);
        db=new DbHelper(SyncService.this);
        cd=new ConnectionDetector(SyncService.this);
        sync_data=new SyncData(SyncService.this);


    }

    @Override

    public void onStart(Intent intent, int startId) {

        Toast.makeText(this, "Sync Service Started", Toast.LENGTH_SHORT).show();

        handler= new Handler();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        //Toast.makeText(this, "Tracking Started", Toast.LENGTH_LONG).show();

        startTimer();


        return START_STICKY;

    }

    @Override

    public void onDestroy() {

        if(timer!=null)
        {
            timer.cancel();
        }



        Toast.makeText(this, "Sync  Service Destroyed", Toast.LENGTH_LONG).show();

    }

    public void startTimer() {

        timer = new Timer();


        initializeTimerTask();



    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {

            public void run() {

                handler.post(new Runnable() {

                    public void run()
                    {
                        Log.i("syncc","function excecuted  "+getTime());


                    }

                });

            }

        };

        timer.schedule(timerTask, 5000, 30 * 1000);

    }

并在清单

 <service android:name="mypackage.SyncService" android:process=":my_syn_service" />

并导致错误

java.lang.NoClassDefFoundError: mypackage.SyncService

和错误原因在处理程序行号。

我没有发现错误。我该如何解决这个问题,请帮帮我。在此先感谢:)

1 个答案:

答案 0 :(得分:0)

您的服务同时包含onStart()onStartCommand()。 {1}}在API级别5中已弃用,不应使用。请考虑使用onCreate()。在onStart()设置为23的KitKat设备上,当调用targetSdkVersion时,运行时甚至不会调用onStart()

相关问题