我编写了一个位于“共享方式”菜单中的应用程序(用于快速通过电子邮件向自己发送指向我在网络上找到的内容或在 RSS 阅读器中查看的内容)为此,我使用了一个 intent.action.SEND 意图过滤器:
<activity
android:name="uk.co.baroquedub.checkit.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
这是 MainActivity 包,它从 Intent 中获取页面标题和 url,并使用单独的 GMailSender 类直接通过电子邮件向我发送此信息:
package uk.co.baroquedub.checkit;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private static Dialog dialog;
String title;
String url;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
String action = intent.getAction();
// if this is from the share menu
if (Intent.ACTION_SEND.equals(action)) {
title = intent.getStringExtra(Intent.EXTRA_SUBJECT);
url = intent.getStringExtra(Intent.EXTRA_TEXT);
// Flipboard fix (remove title in URL)
url = url.replace(title, "");
if (url != null){
url = title+"\n"+url;
} else {
url = "error getting URL";
}
// Asynch Task
doSendTask task = new doSendTask();
task.execute(new String[] { url });
}
}
protected void showDialog (String response){
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(response);
Button button = (Button) dialog.findViewById(R.id.Button01);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
finish();
}
});
dialog.show();
}
private class doSendTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
String senderPassword = getResources().getString(R.string.senderPassword);
String senderEmail = getResources().getString(R.string.senderEmail);
String recipientEmail = getResources().getString(R.string.recipientEmail);
String subjectText = getResources().getString(R.string.subjectText);
GMailSender sender = new GMailSender(senderEmail, senderPassword);
try {
sender.sendMail(subjectText,
url,
senderEmail,
recipientEmail);
response = "Email sent";
} catch (Exception e) {
//Log.e("SendMail", e.getMessage(), e);
response = "Error sending email";
}
return response;
}
@Override
protected void onPostExecute(String result) {
showDialog(result);
}
}
@Override
public void onDestroy() {
super.onDestroy();
/*
* Kill application when the root activity is killed.
*/
UIHelper.killApp(true);
}
}
版本 1 运行良好,但我从“onCreate”中发送电子邮件,这意味着在“已发送电子邮件”通知出现之前,手机的浏览器将无响应(我无法滚动或导航到新页面)。然后我更改了代码(如上所述)以将电子邮件发送代码放在 AsyncTask 类中 - 但是尽管应用程序仍然可以工作,但浏览器仍然没有响应,直到出现对话框。AsyncTask 似乎没有任何区别。
谁能解释原因,并希望提出解决方案?