▼Androidメモ▼
他のアプリのリソース取得とファイル読み書き


他アプリのリソース取得とファイル読み書きを行うプログラムを作成する。
2つのアプリを作成する。

アプリA「SharedEx」はアプリB「SharedSubEx」のイメージリソースを取得して画面に表示する。
sharedUserIdが同じかつ同じ証明書の時、リソース取得が可能。

アプリB「SharedSubEx」はアプリA「SharedEx」のシステムファイルの読み書きを行う。
sharedUserIdがアクセス対象のアプリのパッケージ名と同じ時、ファイル読み書き可能。



アプリBのリソース
プロジェクトの「res/drawable-nodpi」に「sample.png」を配置。

sample.png


アプリAのソースコード
SharedEx.java
package net.npaka.sharedex;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ImageView;

//他のアプリのリソースの取得
public class SharedEx extends Activity {
    private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT;
    //初期化
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //レイアウトの生成
        LinearLayout layout=new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255,255,255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout); 

        //テキストビューの生成
        TextView textView=new TextView(this);
        textView.setText("SharedEx");
        textView.setTextSize(16.0f);                  
        textView.setTextColor(Color.rgb(0,0,0));
        textView.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        layout.addView(textView);

        try {
            //他のアプリのリソースの取得
            Context c=this.createPackageContext(
                "net.npaka.sharedsubex",
                Context.CONTEXT_RESTRICTED);
            Resources res=c.getResources();
            Drawable drawable=res.getDrawable(
                net.npaka.sharedsubex.R.drawable.sample);
        
            //イメージビューの生成
            ImageView imageView=new ImageView(this);
            imageView.setImageDrawable(drawable);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
            layout.addView(imageView);
        } catch (Exception e) {
            showDialog(this,"エラー",
                "SharedSubExのコンテキスト取得に失敗しました ");
        }        
    }  

    //ダイアログの表示
    private static void showDialog(final Activity 
        activity,String title,String text) {
        AlertDialog.Builder ad=new AlertDialog.Builder(activity);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.setPositiveButton("OK",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int whichButton) {
                activity.setResult(Activity.RESULT_OK);
            }
        });
        ad.create();
        ad.show();
    }
}

net.npaka.sharedsubex.R.java
//SharedSubExプロジェクトのgenのR.javaをコピー
package net.npaka.sharedsubex;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
        public static final int sample=0x7f020001;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.npaka.sharedex"
    android:versionCode="1"
    android:versionName="1.0" 
    android:sharedUserId="net.npaka.sharedex">
    <application 
        android:icon="@drawable/icon" 
        android:label="@string/app_name">
        <activity 
            android:name=".SharedEx"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="7" />
</manifest> 

アプリBのソースコード
SharedSubEx.java
package net.npaka.sharedsubex;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

//他のアプリのファイルの読み書き
public class SharedSubEx extends Activity 
    implements View.OnClickListener {
    public final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT;
    public final static int FP=LinearLayout.LayoutParams.FILL_PARENT;
    private EditText editText;//エディットテキスト
    private Button   btnWrite;//書き込みボタン
    private Button   btnRead; //読み込みボタン
    
    //初期化
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //レイアウトの生成
        LinearLayout layout=new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255,255,255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);            
        
        //エディットテキストの生成
        editText=new EditText(this);
        editText.setText("",EditText.BufferType.NORMAL);
        editText.setLayoutParams(new LinearLayout.LayoutParams(FP,WC));
        layout.addView(editText);

        //書き込みボタンの生成
        btnWrite=new Button(this);
        btnWrite.setText("書き込み");
        btnWrite.setOnClickListener(this);
        btnWrite.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        layout.addView(btnWrite);

        //読み込みボタンの生成
        btnRead=new Button(this);
        btnRead.setText("読み込み");
        btnRead.setOnClickListener(this);
        btnRead.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        layout.addView(btnRead); 
    }

    //ボタンクリックイベントの処理
    public void onClick(View v) {
        //他のアプリのコンテキストの取得
        Context c=null;
        try {
            c=this.createPackageContext(
                "net.npaka.sharedex",
                Context.CONTEXT_RESTRICTED);
        } catch (Exception e) {
            showDialog(this,"エラー",
                "SharedExのコンテキスト取得に失敗しました ");
            return;
        }
    
        if (v==btnWrite) {
            try {
                String str=editText.getText().toString();
                str2file(c,str,"test.txt");
            } catch (Exception e) {
                showDialog(this,"エラー","書き込み失敗しました ");
            }            
        } else  if (v==btnRead) {
            try {
                String str=file2str(c,"test.txt");
                editText.setText(str,TextView.BufferType.EDITABLE);
            } catch (Exception e) {
                showDialog(this,"エラー","読み込み失敗しました ");
            }            
        }
    }     
    
    //文字列→ファイル
    private static void str2file(Context context,
        String str,String fileName) throws Exception {
        data2file(context,str.getBytes(),fileName);
    }      

    //ファイル→文字列
    private static String file2str(Context context,
        String fileName) throws Exception {  
        byte[] w=file2data(context,fileName);
        return new String(w);
    }    
    
    //バイトデータ→ファイル
    private static void data2file(Context context,
        byte[] w,String fileName) throws Exception {
        OutputStream out=null;
        try {
            out=context.openFileOutput(fileName,
                Context.MODE_PRIVATE);
            out.write(w,0,w.length);
            out.close();
        } catch (Exception e) {
            try {
                if (out!=null) out.close();
            } catch (Exception e2) {
            }
            throw e;
        }
    } 
    
    //ファイル→バイトデータ
    private static byte[] file2data(Context context,
        String fileName) throws Exception {
        int size;
        byte[] w=new byte[1024]; 
        InputStream in=null;
        ByteArrayOutputStream out=null;
        try {
            in=context.openFileInput(fileName);
            out=new ByteArrayOutputStream();
            while (true) {
                size=in.read(w);
                if (size<=0) break;
                out.write(w,0,size);
            }
            out.close();
            in.close();
            return out.toByteArray();
        } catch (Exception e) {
            try {
                if (in!=null) in.close();
                if (out!=null) out.close();
            } catch (Exception e2) {
            }
            throw e;
        }
    }
    
    //ダイアログの表示
    private static void showDialog(final Activity 
        activity,String title,String text) {
        AlertDialog.Builder ad=new AlertDialog.Builder(activity);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.setPositiveButton("OK",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int whichButton) {
                activity.setResult(Activity.RESULT_OK);
            }
        });
        ad.create();
        ad.show();
    }    
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.npaka.sharedsubex"
    android:versionCode="1"
    android:versionName="1.0" 
    android:sharedUserId="net.npaka.sharedex">
    <application 
        android:icon="@drawable/icon" 
        android:label="@string/app_name">
        <activity 
            android:name=".SharedSubEx"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="7" />
</manifest> 


−戻る−