在Android中每隔X小时运行一次文件/功能,无需打开应用

时间:2015-08-11 16:32:38

标签: java android cron

我想知道当应用关闭且未在后台打开时,是否有办法在我的应用中运行功能或文件..

我会解释,例如,在网页开发中有一个名为cronjobs的东西,它允许每次运行存储在我的服务器上的文件,即使我没有打开实际的网站就设置了..

我想知道是否有什么东西允许我在Android上做同样的事情?

1 个答案:

答案 0 :(得分:0)

此类扩展了Service,在此类中,即使应用程序已关闭,也会在后台完成图像上传:

public class UploadPhotoService extends Service {
IBinder mBinder = new LocalBinder();
String url;
//Notification n;

public class LocalBinder extends Binder {
}

@Override
public void onCreate() {
    super.onCreate();
}


public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if(intent!=null) {
        if(intent.hasExtra("url")) {
    url = intent.getStringExtra("url");
    int id = 1;
    // Issues the notification
    // here you do this if you want a service that constantly notifies the user of what is happening ( ex: music player)
    //n = new NotificationCompat.Builder(this).setContentTitle("Workee")
            .setContentText("Uploading Image")
            .setProgress(0, 0, true)
            .setAutoCancel(false)
            .setSmallIcon(R.drawable.workee_logo).build();
    //startForeground(id, n);
    // execute the async task
    uploadPhoto();
    return START_STICKY;
        }
    }
    return 0 ;
}


@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}


@Override
public void onDestroy() {
    super.onDestroy();
    //stopForeground(true);
    stopSelf(1);
}

public void uploadPhoto() {
    new AsyncTask<Void, Void, String>() {

        @Override
        protected String doInBackground(Void... voids) {
            Server s = new Server(UploadPhotoService.this);
            return s.photoUpload(url);
        }

        @Override
        public void onPostExecute(String result) {

        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}

这是您致电服务的方式: 在这里,我从片段中调用服务:

intent = new Intent(getActivity(), UploadPhotoService.class);
        // I hvae the image path as an extra for the service to upload the image
        intent.putExtra("url", selectedImagePath);
        getActivity().startService(intent);

更重要的是,当您声明服务时,还必须在清单中声明如下:

<service android:name=".services.UploadPhotoService" />