使用活动识别

时间:2014-07-23 11:24:12

标签: android activity-recognition

我想实现一个需要实现我学习的活动识别的应用程序,并按照developer.android.com中的步骤,每当我运行代码时,它会不断显示"启动活动识别(这是我的应用程序)名)"相反,以显示应用程序正在运行。如果我点击日食上的任何东西它只是卡住并关闭窗口

我有什么需要做的吗? 这是我的代码

package com.example.activityrecignition;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.ActivityRecognitionClient;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;


public class MainActivity extends FragmentActivity implements  ConnectionCallbacks,OnConnectionFailedListener {

 public static final int MILLISECONDS_PER_SECOND = 1000;
    public static final int DETECTION_INTERVAL_SECONDS = 20;
    public static final int DETECTION_INTERVAL_MILLISECONDS =
            MILLISECONDS_PER_SECOND * DETECTION_INTERVAL_SECONDS;
  private final static int
  CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

  private PendingIntent mActivityRecognitionPendingIntent;
    // Store the current activity recognition client
    private ActivityRecognitionClient mActivityRecognitionClient;

    private Context mContext;
    private Intent intent;
    TextView tv;
     ActivityRecognitionIntentService ar;

    private boolean mInProgress;

    public enum REQUEST_TYPE {START, STOP}
    private REQUEST_TYPE mRequestType;
    Intent i;
    @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mActivityRecognitionClient =
            new ActivityRecognitionClient(mContext, this, this);
    mActivityRecognitionPendingIntent =
            PendingIntent.getService(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    tv=(TextView) findViewById(R.id.activityname);
    mInProgress=false;
    ar.onHandleIntent(i);
}

@SuppressLint("NewApi") public static class ErrorDialogFragment extends DialogFragment {

 private Dialog mDialog;
 @SuppressLint("NewApi") public ErrorDialogFragment() {
  super();
  mDialog = null;
}

 public void setDialog(Dialog dialog) {
  mDialog = dialog;
}

  @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {


}
 }
@Override
 protected void onActivityResult(
   int requestCode, int resultCode, Intent data) {
  switch (requestCode) {

  case CONNECTION_FAILURE_RESOLUTION_REQUEST :
      switch (resultCode) {
          case Activity.RESULT_OK :


          break;
      }

}

}

private boolean servicesConnected() {

 int resultCode =
      GooglePlayServicesUtil.
              isGooglePlayServicesAvailable(this);

 if (ConnectionResult.SUCCESS == resultCode) {
     Log.d("Activity Recognition",
          "Google Play services is available.");
  return true;
 } else {
    Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
          resultCode,
          this,
          CONNECTION_FAILURE_RESOLUTION_REQUEST);


  if (errorDialog != null) {
      // Create a new DialogFragment for the error dialog
      ErrorDialogFragment errorFragment =
              new ErrorDialogFragment();
      // Set the dialog in the DialogFragment
      errorFragment.setDialog(errorDialog);
      // Show the error dialog in the DialogFragment
      errorFragment.show(
              getSupportFragmentManager(),
              "Activity Recognition");
  }
  return false;
 }
}
public class ActivityRecognitionIntentService extends IntentService {

public ActivityRecognitionIntentService(String name) {
    super(name);
    // TODO Auto-generated constructor stub
}
private String getNameFromType(int activityType) {
    switch(activityType) {
        case DetectedActivity.IN_VEHICLE:
            return "in_vehicle";
        case DetectedActivity.ON_BICYCLE:
            return "on_bicycle";
        case DetectedActivity.ON_FOOT:
            return "on_foot";
        case DetectedActivity.STILL:
            return "still";
        case DetectedActivity.UNKNOWN:
            return "unknown";
        case DetectedActivity.TILTING:
            return "tilting";
    }
    return "unknown";
}
@Override
protected void onHandleIntent(Intent intent) {

    // If the incoming intent contains an update
    if (ActivityRecognitionResult.hasResult(intent)) {
        // Get the update
        ActivityRecognitionResult result =
                ActivityRecognitionResult.extractResult(intent);
        // Get the most probable activity
        DetectedActivity mostProbableActivity =
                result.getMostProbableActivity();
        /*
         * Get the probability that this activity is the
         * the user's actual activity
         */
        int confidence = mostProbableActivity.getConfidence();
        /*
         * Get an integer describing the type of activity
         */
        int activityType = mostProbableActivity.getType();
        String activityName = getNameFromType(activityType);
        tv.setText(activityName);
        /*
         * At this point, you have retrieved all the information
         * for the current update. You can display this
         * information to the user in a notification, or
         * send it to an Activity or Service in a broadcast
         * Intent.
         */

    } else {
        /*
         * This implementation ignores intents that don't contain
         * an activity update. If you wish, you can report them as
         * errors.
         */
        tv.setText("There are no updates!!!");
    }

}

}

public void onClick(View v){
    if(v.getId()==R.id.Start){
        startUpdates();
    }
    if(v.getId()==R.id.Stop){
        stopUpdates();
    }
}

public void startUpdates() {
    // Check for Google Play services
    mRequestType = REQUEST_TYPE.START;

    if (!servicesConnected()) {
        return;
    }
    // If a request is not already underway
    if (!mInProgress) {
        // Indicate that a request is in progress
        mInProgress = true;
        // Request a connection to Location Services
        mActivityRecognitionClient.connect();
    //
    } else {
        /*
         * A request is already underway. You can handle
         * this situation by disconnecting the client,
         * re-setting the flag, and then re-trying the
         * request.
         */

        mInProgress = true;
        mActivityRecognitionClient.disconnect();
        mActivityRecognitionClient.requestActivityUpdates(
                DETECTION_INTERVAL_MILLISECONDS,
                mActivityRecognitionPendingIntent);
    }
}



@Override
public void onConnected(Bundle dataBundle) {
    // TODO Auto-generated method stub
     mActivityRecognitionClient.requestActivityUpdates(
                DETECTION_INTERVAL_MILLISECONDS,
                mActivityRecognitionPendingIntent);
        /*
         * Since the preceding call is synchronous, turn off the
         * in progress flag and disconnect the client
         */
        mInProgress = false;
        mActivityRecognitionClient.disconnect();
        switch (mRequestType) {
        case START :
            /*
             * Request activity recognition updates using the
             * preset detection interval and PendingIntent.
             * This call is synchronous.
             */
            mActivityRecognitionClient.requestActivityUpdates(
                    DETECTION_INTERVAL_MILLISECONDS,
                    mActivityRecognitionPendingIntent);
            break;
        case STOP :
            mActivityRecognitionClient.removeActivityUpdates(
                    mActivityRecognitionPendingIntent);

            /*
             * An enum was added to the definition of REQUEST_TYPE,
             * but it doesn't match a known case. Throw an exception.
             */
            default :
            try {
                throw new Exception("Unknown request type in onConnected().");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
    }
}

@Override
public void onDisconnected() {
    // TODO Auto-generated method stub
    mInProgress = false;
    // Delete the client
    mActivityRecognitionClient = null;
}

 @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Turn off the request flag
        mInProgress = false;
        /*
         * If the error has a resolution, start a Google Play services
         * activity to resolve it.
         */
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(
                        this,
                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        // If no resolution is available, display an error dialog
        } else {
            // Get the error code
            int errorCode = connectionResult.getErrorCode();
            // Get the error dialog from Google Play services
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
                    errorCode,
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            // If Google Play services can provide an error dialog
            if (errorDialog != null) {
                // Create a new DialogFragment for the error dialog
                ErrorDialogFragment errorFragment =
                        new ErrorDialogFragment();
                // Set the dialog in the DialogFragment
                errorFragment.setDialog(errorDialog);
                // Show the error dialog in the DialogFragment
                errorFragment.show(
                        getSupportFragmentManager(),
                        "Activity Recognition");
            }
        }

    }



 public void stopUpdates() {
        // Set the request type to STOP
        mRequestType = REQUEST_TYPE.STOP;
        /*
         * Test for Google Play services after setting the request type.
         * If Google Play services isn't present, the request can be
         * restarted.
         */
        if (!servicesConnected()) {
            return;
        }
        // If a request is not already underway
        if (!mInProgress) {
            // Indicate that a request is in progress
            mInProgress = true;
            // Request a connection to Location Services
            mActivityRecognitionClient.connect();
        //
        } else {
            /*
             * A request is already underway. You can handle
             * this situation by disconnecting the client,
             * re-setting the flag, and then re-trying the
             * request.
             */
        }

    }

}

1 个答案:

答案 0 :(得分:0)

实际上我超出了GC开销限制问题。我得到了解决方案here