繁体   English   中英

Android应用程序的启动活动

[英]starting activity for Android application

我目前正在开发一个Android应用,该应用集成了Google日历。 如我们所知,如果我们想选择一个活动作为开始活动,我们只需添加“意图过滤器” thing。 我是在“目标网页”活动中添加的,但是当我在模拟器上调试时,它将在“我的日历”活动部分自动添加“意图过滤器”,并注释掉在“目标网页”中添加的那个。

这是AndroidManifest.xml中的代码

        <activity
        android:name="com.example.dylicious.mydoctors.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.dylicious.mydoctors.ViewDocActivity"
        android:label="@string/title_activity_view_doc" >
    </activity>
    <activity
        android:name="com.example.dylicious.mydoctors.ViewDoctorProf"
        android:label="@string/title_activity_view_doctor_prof" >
    </activity>
    <activity
        android:name="com.example.dylicious.mydoctors.StorePatientProfile"
        android:label="@string/title_activity_store_patient_profile" >
    </activity>
    <activity
        android:name="com.example.dylicious.mydoctors.ViewPatientProfile"
        android:label="@string/title_activity_view_patient_profile" >
    </activity>
    <activity
        android:name="com.example.dylicious.mydoctors.AppointmentActivity"
        android:label="@string/title_activity_appointment" >
        <!--<intent-filter>-->
            <!--<action android:name="android.intent.action.MAIN" />-->

            <!--<category android:name="android.intent.category.LAUNCHER" />-->
        <!--</intent-filter>-->
    </activity>

这是我编辑的,AppointmentActivity是Google日历的一部分。 我一直在注释掉并删除AppointmentActivity中的部分以及干净的解决方案等,但是它什么都没用。 我只是想检查一下我是否错过了任何事情,因为我只是Android App Development领域的新手。 提前谢谢一堆!

虽然这是AppointmentActivity.java的类

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesUtil;
    import com.google.api.client.extensions.android.http.AndroidHttp;
    import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.ExponentialBackOff;


    import com.google.api.services.calendar.CalendarScopes;

    import android.accounts.AccountManager;
    import android.app.Activity;
    import android.app.Dialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.graphics.Typeface;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.text.method.ScrollingMovementMethod;
    import android.view.ViewGroup;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import java.util.Arrays;
    import java.util.List;

public class AppointmentActivity extends Activity {

com.google.api.services.calendar.Calendar mService;

GoogleAccountCredential credential;
private TextView mStatusText;
private TextView mResultsText;
ProgressDialog mProgress;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };

/**
 * Create the main activity.
 * @param savedInstanceState previously saved instance data.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout activityLayout = new LinearLayout(this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    activityLayout.setLayoutParams(lp);
    activityLayout.setOrientation(LinearLayout.VERTICAL);
    activityLayout.setPadding(16, 16, 16, 16);

    ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    mStatusText = new TextView(this);
    mStatusText.setLayoutParams(tlp);
    mStatusText.setTypeface(null, Typeface.BOLD);
    mStatusText.setText("Retrieving data...");
    activityLayout.addView(mStatusText);

    mResultsText = new TextView(this);
    mResultsText.setLayoutParams(tlp);
    mResultsText.setPadding(16, 16, 16, 16);
    mResultsText.setVerticalScrollBarEnabled(true);
    mResultsText.setMovementMethod(new ScrollingMovementMethod());
    activityLayout.addView(mResultsText);

    mProgress = new ProgressDialog(this);
    mProgress.setMessage("Calling Google Calendar API ...");

    setContentView(activityLayout);

    // Initialize credentials and service object.
    SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
    credential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff())
            .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

    mService = new com.google.api.services.calendar.Calendar.Builder(
            transport, jsonFactory, credential)
            .setApplicationName("Google Calendar API Android Quickstart")
            .build();
}


/**
 * Called whenever this activity is pushed to the foreground, such as after
 * a call to onCreate().
 */
@Override
protected void onResume() {
    super.onResume();
    if (isGooglePlayServicesAvailable()) {
        refreshResults();
    } else {
        mStatusText.setText("Google Play Services required: " +
                "after installing, close and relaunch this app.");
    }
}

/**
 * Called when an activity launched here (specifically, AccountPicker
 * and authorization) exits, giving you the requestCode you started it with,
 * the resultCode it returned, and any additional data from it.
 * @param requestCode code indicating which activity result is incoming.
 * @param resultCode code indicating the result of the incoming
 *     activity result.
 * @param data Intent (containing result data) returned by incoming
 *     activity result.
 */
@Override
protected void onActivityResult(
        int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case REQUEST_GOOGLE_PLAY_SERVICES:
            if (resultCode != RESULT_OK) {
                isGooglePlayServicesAvailable();
            }
            break;
        case REQUEST_ACCOUNT_PICKER:
            if (resultCode == RESULT_OK && data != null &&
                    data.getExtras() != null) {
                String accountName =
                        data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                if (accountName != null) {
                    credential.setSelectedAccountName(accountName);
                    SharedPreferences settings =
                            getPreferences(Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(PREF_ACCOUNT_NAME, accountName);
                    editor.commit();
                }
            } else if (resultCode == RESULT_CANCELED) {
                mStatusText.setText("Account unspecified.");
            }
            break;
        case REQUEST_AUTHORIZATION:
            if (resultCode != RESULT_OK) {
                chooseAccount();
            }
            break;
    }

    super.onActivityResult(requestCode, resultCode, data);
}

/**
 * Attempt to get a set of data from the Google Calendar API to display. If the
 * email address isn't known yet, then call chooseAccount() method so the
 * user can pick an account.
 */
private void refreshResults() {
    if (credential.getSelectedAccountName() == null) {
        chooseAccount();
    } else {
        if (isDeviceOnline()) {
            mProgress.show();
            new ApiAsyncTask(this).execute();
        } else {
            mStatusText.setText("No network connection available.");
        }
    }
}

/**
 * Clear any existing Google Calendar API data from the TextView and update
 * the header message; called from background threads and async tasks
 * that need to update the UI (in the UI thread).
 */
public void clearResultsText() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mStatusText.setText("Retrieving data…");
            mResultsText.setText("");
        }
    });
}

/**
 * Fill the data TextView with the given List of Strings; called from
 * background threads and async tasks that need to update the UI (in the
 * UI thread).
 * @param dataStrings a List of Strings to populate the main TextView with.
 */
public void updateResultsText(final List<String> dataStrings) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (dataStrings == null) {
                mStatusText.setText("Error retrieving data!");
            } else if (dataStrings.size() == 0) {
                mStatusText.setText("No data found.");
            } else {
                mStatusText.setText("Data retrieved using" +
                        " the Google Calendar API:");
                mResultsText.setText(TextUtils.join("\n\n", dataStrings));
            }
        }
    });
}

/**
 * Show a status message in the list header TextView; called from background
 * threads and async tasks that need to update the UI (in the UI thread).
 * @param message a String to display in the UI header TextView.
 */
public void updateStatus(final String message) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mStatusText.setText(message);
        }
    });
}

/**
 * Starts an activity in Google Play Services so the user can pick an
 * account.
 */
private void chooseAccount() {
    startActivityForResult(
            credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}

/**
 * Checks whether the device currently has a network connection.
 * @return true if the device has a network connection, false otherwise.
 */
private boolean isDeviceOnline() {
    ConnectivityManager connMgr =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected());
}

/**
 * Check that Google Play services APK is installed and up to date. Will
 * launch an error dialog for the user to update Google Play Services if
 * possible.
 * @return true if Google Play Services is available and up to
 *     date on this device; false otherwise.
 */
private boolean isGooglePlayServicesAvailable() {
    final int connectionStatusCode =
            GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
        showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
        return false;
    } else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
        return false;
    }
    return true;
}

/**
 * Display an error dialog showing that Google Play Services is missing
 * or out of date.
 * @param connectionStatusCode code describing the presence (or lack of)
 *     Google Play Services on this device.
 */
void showGooglePlayServicesAvailabilityErrorDialog(
        final int connectionStatusCode) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
                    connectionStatusCode,
                    AppointmentActivity.this,
                    REQUEST_GOOGLE_PLAY_SERVICES);
            dialog.show();
        }
    });
}

}

谢谢!!

AppointmentActivity AndroidManifest文件声明中省略intent-filter 因为调用动作android:name="android.intent.action.MAIN"定义了应用程序中的主入口点,而android:name="android.intent.category.LAUNCHER"意味着应在应用程序中列出入口点启动器,因此您会看到该应用程序中没有2个主要入口点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM