5

サービス内にある asynctask で getFilesDir() を使用できません。この投稿を見ました: Android: AsyncTask のファイルへの書き込み アクティビティで問題を解決しますが、サービスでこれを行う方法が見つかりません。サービスで asynctask を使用して内部ストレージ ファイルに書き込む方法は? これは asynctask の私のコードです:

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

2 に答える 2

2

両方ともServiceからもActivity拡張するContextWrapperため、getFilesDir()メソッドがあります。Service のインスタンスをAsyncTaskobject に渡すと解決します。

何かのようなもの:

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

AsyncTask を作成するときは、現在の Service の参照を渡します ( AsyncTaskObjectfrom 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;
        }
    }
}
于 2013-09-05T12:05:30.710 に答える
0

getFileDir()サービスを開始するときは、次のように提供される文字列パスを渡す必要があると思います。

Intent serviceIntent = new Intent(this,YourService.class); 
serviceIntent.putExtra("fileDir", getFileDir());

あなたのサービスインonStartメソッドでは、

Bundle extras = intent.getExtras(); 
if(extras == null)
    Log.d("Service","null");
else
{
    Log.d("Service","not null");
    String fileDir = (String) extras.get("fileDir");
}
于 2013-09-05T12:06:56.663 に答える