Java 如何根据活动识别结果启动服务

Java 如何根据活动识别结果启动服务,java,android,service,activity-recognition,Java,Android,Service,Activity Recognition,如果从返回的活动识别返回的检测到的活动在车内,我正在尝试启动服务。我下载了一个代码示例 发件人: 但我不确定在哪里输入代码来启动我的服务。 我试图使用活动识别在后台检查用户活动,然后 在后台启动服务 活动识别内容服务类 public class ActivityRecognitionIntentService extends IntentService { //LogCat private static final String TAG = ActivityRecognitionInten

如果从返回的活动识别返回的检测到的活动在车内,我正在尝试启动服务。我下载了一个代码示例 发件人:

但我不确定在哪里输入代码来启动我的服务。 我试图使用活动识别在后台检查用户活动,然后 在后台启动服务

活动识别内容服务类

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";
}
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);
}
}

main活动类

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";
}
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);
}
}

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);
    }

}
别忘了把你的接收人添加到你的舱单上。
我建议您从活动层而不是服务层开始活动

不太可能有人会为了帮助你而费心阅读教程。请发布相关的代码片段,您在问题中尝试了哪些,哪些不起作用。好的,对不起,请给我一秒钟时间,我发布我的代码。我看起来所有的代码都在github中可用-在这个代码示例中,启动服务的代码不是吗?我不确定@kristy Welsh您在哪里看到了这些代码。我发现这段代码的唯一地方是我发布的start TutsBerry链接。如果你发现了有帮助的代码,请在这里发布链接。谢谢。我对安卓系统还不太熟悉。这是我的第一个应用程序,所以我觉得很难让它正常工作。非常感谢你的回答。我会尽快试用并回复你,希望它对我有效,我会接受答案!:)非常感谢,我已经尝试了很长一段时间来让这个工作,但它证明是困难的,因为我缺乏一般的android知识,因为我只是新的。欢迎。如果你有任何问题,请告诉我。我试图使代码尽可能简单,以便您理解您需要做什么。我看到您在回答的末尾写道,您建议我从活动开始服务。我的意图是,用户可以将其设备锁定在口袋中,然后如果活动识别检测到用户在车内,我的服务将启动。我说的对吗?如果我使用活动,应用程序必须是打开的,用户必须在场。或者我可以像你一样使用一个广播接收器,但它可以自己检测活动并启动服务。所有这些都是在后台完成的,比那更复杂。你必须考虑什么会触发这些行为?如果你从后台开始活动,你必须小心,因为某些行为是没有意义的。您将从后台打开活动,但用户在开始使用手机之前不会真正看到?您可以从后台打开它们,但如果您使用PendingEvents,并检查设备是否处于允许该活动在不崩溃的情况下打开的状态,则会更好。非常抱歉,我如何将您的代码链接到活动识别api代码?