-4

当用户使用 Android 下载文件时,我希望启动我的自定义活动以打开该文件。例如,当文件启动时,我的自定义活动应显示在“使用完成操作”警报框中。

有什么例子可以看看这是怎么做到的吗?

4

1 回答 1

1

If I am correct, this will be what you want in your manifest:

<activity
     android:name=".NameOfYourActivity"
     android:label="@string/app_name" >
            <intent-filter>
                  <action android:name="android.intent.action.VIEW" />
                  <category android:name="android.intent.category.DEFAULT" />
                  <data android:mimeType="text/plain" />
            </intent-filter>
</activity>

For more information, read Intents and Intent Filters from the developer website.

Also, here is a sample of an activity you could use to display a file.

public class MIMEsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    //Get the intent that has the information about the file.
    Intent sender = getIntent();

    //In this example I'm simply displaying the file's contents
    //in a TextView.
    TextView view = (TextView) findViewById(R.id.textview);

    //Check to see if there was an intent sent.
    if(sender != null) {

        //Get the file.
        File file = new File(sender.getData().getPath());

        /*
            DO STUFF HERE WITH THE FILE
            I load the text of the file and send it
            to the TextView.
        */
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
            //You'll need to add proper error handling here
        }

        view.setText("PATH: " + sender.getData().getPath() + "\n\n" + text);
        //Done doing stuff.
    }
    //If an intent was not sent, do something else.
    else {
        view.setText("You did not get a file!");
    }

}

}

于 2012-06-30T21:47:05.323 回答