如何根据活动识别的结果开始服务

时间:2015-10-12 14:21:58

标签: java android service activity-recognition

如果从返回的活动识别返回的DetectedActivity是IN_VEHICLE,我正在尝试启动服务。我已经下载了一个代码示例 来自: http://tutsberry.com/activity-recognition-implementation-on-android/

但我不知道在哪里放入代码来启动我的服务。 我正在尝试使用活动识别检查后台的用户活动,然后 在后台启动所有服务。

ActivityRecognitionIntentService类

public class ActivityRecognitionIntentService extends IntentService {


//LogCat
private static final String TAG = ActivityRecognitionIntentService.class.getSimpleName();

public ActivityRecognitionIntentService() {
    super("ActivityRecognitionIntentService");
}

protected void onHandleIntent(Intent intent) {
    if (ActivityRecognitionResult.hasResult(intent)) {
        //Extract the result from the Response
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
        DetectedActivity detectedActivity = result.getMostProbableActivity();

        //Get the Confidence and Name of Activity
        int confidence = detectedActivity.getConfidence();
        String mostProbableName = getActivityName(detectedActivity.getType());


        //Fire the intent with activity name & confidence
        Intent i = new Intent("ImActive");
        i.putExtra("activity", mostProbableName);
        i.putExtra("confidence", confidence);

        Log.d(TAG, "Most Probable Name : " + mostProbableName);
        Log.d(TAG, "Confidence : " + confidence);

        //Send Broadcast to be listen in MainActivity
        this.sendBroadcast(i);

    } else {
        Log.d(TAG, "Intent had no data returned");
    }
}

//Get the activity name
private String getActivityName(int type) {
    switch (type) {
        case DetectedActivity.IN_VEHICLE:
            return "In Vehicle";
        case DetectedActivity.ON_BICYCLE:
            return "On Bicycle";
        case DetectedActivity.ON_FOOT:
            return "On Foot";
        case DetectedActivity.WALKING:
            return "Walking";
        case DetectedActivity.STILL:
            return "Still";
        case DetectedActivity.TILTING:
            return "Tilting";
        case DetectedActivity.RUNNING:
            return "Running";
        case DetectedActivity.UNKNOWN:
            return "Unknown";
    }
    return "N/A";
}

}

MainActivity Class

public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{


// LogCat
private static final String TAG = MainActivity.class.getSimpleName();

private Context mContext;
private GoogleApiClient mGApiClient;
private BroadcastReceiver receiver;
private TextView textView;
private TextView tv2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



      textView = (TextView) findViewById(R.id.msg);
    textView.setMovementMethod(new ScrollingMovementMethod());

    tv2 = (TextView) findViewById(R.id.text2);

    //Set the context
    mContext = this;

    //Check Google Play Service Available
    if (isPlayServiceAvailable()) {
        mGApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        //Connect to Google API
        mGApiClient.connect();
    } else {
        Toast.makeText(mContext, "Google Play Service not Available", Toast.LENGTH_LONG).show();
    }

    //Broadcast receiver
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Add current time
            Calendar rightNow = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
            String strDate = sdf.format(rightNow.getTime());
            ;
            String v = strDate + " " +
                    intent.getStringExtra("activity") + " " +
                    "Confidence : " + intent.getExtras().getInt("confidence") + "\n";

            v = textView.getText() + v;
            textView.setText(v);
        }
    };

    //Filter the Intent and register broadcast receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction("ImActive");
    registerReceiver(receiver, filter);

    //Check for Google play services available on device

}

private boolean isPlayServiceAvailable() {
    return GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS;
}





@Override
protected void onDestroy() {

    super.onDestroy();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}



@Override
public void onConnected(Bundle bundle) {
    Intent i = new Intent(this, ActivityRecognitionIntentService.class);
    PendingIntent mActivityRecongPendingIntent = PendingIntent
            .getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Log.d(TAG, "connected to ActivityRecognition");
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);

    //Update the TextView
    textView.setText("Connected to Google Play Services \nWaiting for Active Recognition... \n");

}

@Override
public void onConnectionSuspended(int i) {
    Log.d(TAG, "Suspended to ActivityRecognition");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d(TAG, "Not connected to ActivityRecognition");

    //Disconnect and detach the receiver
    mGApiClient.disconnect();
    unregisterReceiver(receiver);
}

}

1 个答案:

答案 0 :(得分:-1)

MainActivity.java

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends Activity {
    IntentFilter filter;
    BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        filter = new IntentFilter();
        mReceiver = new MyReceiver();
        filter.addAction("IN_VEHICLE"); //Name the action what ever you need to.
        filter.addAction("OTHER_ACTION");
        filter.addAction("YET_ANOTHER_ACTION)");
        registerReceiver(mReceiver, filter); //Register the receiver you define with the actions you want.
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if("IN_VEHICLE_RESPONSE".equals(intent.getAction())){
                //Launch other activities here 
                Intent i = new Intent(getApplicationContext(), InVehicleActivity.class );
                startActivity(i);

            }else if("OTHER_ACTION_RESPONSE".equals(intent.getAction())){
                //Launch desired activity
            }else if("YET_ANOTHER_ACTION_RESPONSE".equals(intent.getAction())){
                //Launch desired activity
            }else{
                //Handle unssuported actions
            }
        }
    }

}

MyIntentService.java

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

public class MyIntentService extends IntentService {

    Bundle extras;

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        extras = intent.getExtras();
        if("IN_VEHICLE".equals(intent.getAction())){
            inVehicle(extras);
            return;
        }
        if("OTHER_ACTION".equals(intent.getAction())){
            //otheraction method
            return;
        }
        if("YET_ANOTHER_ACTION".equals(intent.getAction())){
            //yetanotheraction method
            return;
        }

    }

    private void inVehicle(Bundle extras) {
        //do work
        //do work
        Intent intent = new Intent();
        intent.setAction("IN_VEHICLE_RESPONSE");
        //put all other desired stuff in intent
        getApplicationContext().sendBroadcast(intent);
    }

}

不要忘记将接收器添加到清单中。 我建议您从Activity not Service层启动Activities。