如何写入文件中,在服务上的AsyncTask的内部存储? [英] How to write to a file in the internal storage with an asynctask in a service?

查看:122
本文介绍了如何写入文件中,在服务上的AsyncTask的内部存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能在AsyncTask的是在一个服务使用getFilesDir()。
我看到这个帖子:
安卓:写在AsyncTask的文件
它解决了问题的活动,但我不找到一种方法,在服务做到这一点。
如何写在服务上的AsyncTask的内部存储的文件?
这是我的code。在AsyncTask的:

 文件fil​​e =新的文件(getFilesDir()+/IP.txt);


解决方案

两个服务活动从延长 ContextWrapper 一样,所以它具有 getFilesDir()方法。传递服务的一个实例来的AsyncTask 对象将解决这个问题。

是这样的:

 文件fil​​e =新的文件(myContextRef.getFilesDir()+/IP.txt);

当您正在创建的AsyncTask的电流传递服务的引用(我假设你在创建 AsyncTaskObject 从Service):

 进口的java.io.File;进口android.app.Service;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.IBinder;公共类为MyService扩展服务{
    @覆盖
    公众的IBinder onBind(意向意图){
        返回null;
    }    保护无效useFileAsyncTask(){
        FileWorkerAsyncTask任务=新FileWorkerAsyncTask(本);
        task.execute();
    }    私有静态类FileWorkerAsyncTask扩展的AsyncTask<太虚,太虚,太虚> {        私人服务myContextRef;        公共FileWorkerAsyncTask(服务myContextRef){
            this.myContextRef = myContextRef;
        }        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            档案文件=新的文件(myContextRef.getFilesDir()+/IP.txt);
            // 用它 ...
            返回null;
        }
    }
}

I can't use the getFilesDir() in an asynctask which is in a service. I saw this post: Android: Writing to a file in AsyncTask It solves the problem in an activity but i dont find a way to do this in a service. How to write to an internal storage file with an asynctask in a service? This is my code in the asynctask:

  File file = new File(getFilesDir() + "/IP.txt");

解决方案

Both Service and Activity extend from ContextWrapper as well, so it has getFilesDir() method. Passing an instance of Service to AsyncTask object will solve it.

Something like:

File file = new File(myContextRef.getFilesDir() + "/IP.txt");

When you're creating the AsyncTask pass a reference of current Service (I suppose you're creating the AsyncTaskObject from Service):

import java.io.File;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    protected void useFileAsyncTask() {
        FileWorkerAsyncTask task = new FileWorkerAsyncTask(this);
        task.execute();
    }

    private static class FileWorkerAsyncTask extends AsyncTask<Void, Void, Void> {

        private Service myContextRef;

        public FileWorkerAsyncTask(Service myContextRef) {
            this.myContextRef = myContextRef;
        }

        @Override
        protected Void doInBackground(Void... params) {
            File file = new File(myContextRef.getFilesDir() + "/IP.txt");
            // use it ...
            return null;
        }
    }
}

这篇关于如何写入文件中,在服务上的AsyncTask的内部存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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