本例演示如何通过Intent来打开手机sd卡中的word,pdf文件,这里实际上是通过Intent打开手机中能够阅读word,或pdf的应用,让那个应用来打开文件。而不是我们这个例子本身能够打开文件。
直接上代码:
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/btn_open_word"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="打开word" />
<Button
android:id="@+id/btn_open_pdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_below="@+id/btn_open_word"
android:text="打开pdf" />
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Button btnOpenWord;
private Button btnOpenPdf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOpenWord = (Button)findViewById(R.id.btn_open_word);
btnOpenPdf = (Button)findViewById(R.id.btn_open_pdf);
btnOpenWord.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
File file = new File(getSDPath()+"/***.doc");//这里更改为你的名称
Log.e(TAG, "file exsit:"+file.getPath());
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/msword");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this,
"No Application Available to View WORD",
Toast.LENGTH_SHORT).show();
}
}
}
});
btnOpenPdf.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
File file = new File(getSDPath()+"/***.pdf");//这里更改为你的名称
Log.e(TAG, "file exsit:"+file.exists());
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
/**
* 获取sd卡路径
*
* */
private String getSDPath(){
File sdDir = null;
boolean sdCardExist = android.os.Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());//判断sd卡是否存在
if(sdCardExist){
sdDir = Environment.getExternalStorageDirectory();//获取目录
}
Log.e(TAG, "sdCard:"+sdDir.toString());
return sdDir.toString();
}
}
在我的机器Nexus s中,能够通过Document Viewer正常打开word和pdf