计时器不在后台运行

时间:2015-09-22 07:30:02

标签: android csv gps

我正在开发一个应用程序,我想在特定的时间间隔内在csv文件中存储纬度和经度,即使应用程序没有运行。我使用过计时器但数据仅在应用程序运行时存储。这是我的代码。

  String strDate;
FileWriter writer;
String username;
public static double latitude;
public static double longitude;
public static String username1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.app_bar);
    toolbar.setTitle("Welcome");
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Intent intent = getIntent();
    username =  intent.getStringExtra("user");

    SharedPreferences.Editor editor = getSharedPreferences(
            "MyPref", MODE_PRIVATE).edit();

    editor.putString("username", username);
    editor.commit();

    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
    strDate = sdf.format(c.getTime());
    date = (TextView) findViewById(R.id.date);
    time = (TextView) findViewById(R.id.time);


    date.setText(strDate);
    gps = new GPSTracker(MainActivity.this);


    if (gps.canGetLocation()) {

        latitude = gps.getLatitude();
        longitude = gps.getLongitude();


        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
    } else {

        gps.showSettingsAlert();
    }


    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        Handler mnhandler = new Handler();

        @Override
        public void run() {
            mnhandler.post(new Runnable() {
                @Override
                public void run() {
                    SharedPreferences mmm = getSharedPreferences(
                            "MyPref", MODE_PRIVATE);

                   username1 = mmm.getString("username", null);

                    Log.e("mmmmmmmmmmmmmmm", "" + username1);

                    double latitude1 = gps.getLatitude();
                    double longitude1 = gps.getLongitude();
                    //Use ur method which store CSV file
                    File root = Environment.getExternalStorageDirectory();
    File gpxfile = new File(root, "mydata.csv");
    try {
        writer = new FileWriter(gpxfile);
        writeCsvHeader("Username","DateTime", "Latitude", "Longitude");
        writeCsvData(""+username1,"" + strDate, latitude1, longitude1);

        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

                }
            });
        }
    };
    timer.schedule(timerTask, 5000, 10000);

}

private void writeCsvHeader(String user, String h1, String h2, String h3) throws IOException {
    String line = String.format("%s,%s,%s,%s\n",user, h1, h2, h3);
    writer.write(line);
}

private void writeCsvData(String userr,String date, double lat, double lon) throws IOException {
    String line = String.format("%s,%s,%f,%f\n",userr, date, lat, lon);
    writer.write(line);
}

我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

您需要在后台完成工作,并且需要创建后台服务。

使用计时器服务:

public class LocalService extends Service
{
    private static Timer timer = new Timer(); 
    private Context ctx;

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

    public void onCreate() 
    {
          super.onCreate();
          ctx = this; 
          startService();
    }

    private void startService()
    {           
        timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
    }

    private class mainTask extends TimerTask
    { 
        public void run() 
        {
            toastHandler.sendEmptyMessage(0);
        }
    }    

    public void onDestroy() 
    {
          super.onDestroy();
          Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
    }

    private final Handler toastHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
        }
    };    
}