如何在设备启动时使用BroadcastReceivers启动Google API - ActivityRecognitionAPI?

时间:2016-07-11 11:00:33

标签: android google-api broadcastreceiver activity-recognition

我已经使用了这个API,它可以运行。我尝试使用此BroadcastReceiver启动MainActivity,它可以工作。但是当我尝试这个时,它会崩溃我的应用程序。

我是否需要为意图添加标记?在这种情况下如何做到这一点?

我尝试了这些代码,但我的应用在启动时崩溃了:

1)BroadcastReceiver类:

public class startReceiver extends BroadcastReceiver
    implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

public Context appContext;
public GoogleApiClient mApiClient;

@Override
public void onReceive(Context context, Intent intent) {
    appContext = context;

    mApiClient = new GoogleApiClient.Builder(context)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) context)
            .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) context)
            .build();

    mApiClient.connect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Intent intent = new Intent(appContext, ActivityRecognizedService.class);
    PendingIntent pendingIntent = PendingIntent.getService(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 10000, pendingIntent);
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(appContext, "Connection to Google Services suspended!", Toast.LENGTH_LONG).show();
    mApiClient.reconnect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(appContext, "Connection to Google Services failed!", Toast.LENGTH_LONG).show();
    mApiClient.connect();
}

2)ActivityRecognizedService

public class ActivityRecognizedService extends IntentService {

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

public ActivityRecognizedService(String name) {
    super(name);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (ActivityRecognitionResult.hasResult(intent)) {
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
        handleDetectedActivities(result.getProbableActivities());
    }
}

private void handleDetectedActivities(List<DetectedActivity> probableActivities) {
    for (DetectedActivity activity : probableActivities) {
        switch (activity.getType()) {
            case DetectedActivity.IN_VEHICLE: {
                Log.e("ActivityRecogition", "In Vehicle: " + activity.getConfidence());
                break;
            }
            case DetectedActivity.ON_BICYCLE: {
                Log.e("ActivityRecogition", "On Bicycle: " + activity.getConfidence());
                break;
            }
            case DetectedActivity.ON_FOOT: {
                Log.e("ActivityRecogition", "On Foot: " + activity.getConfidence());
                break;
            }
            case DetectedActivity.RUNNING: {
                Log.e("ActivityRecogition", "Running: " + activity.getConfidence());
                break;
            }
            case DetectedActivity.STILL: {
                Log.e("ActivityRecogition", "Still: " + activity.getConfidence());
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                builder.setContentText("Are you walking?");
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setContentTitle(getString(R.string.app_name));
                NotificationManagerCompat.from(this).notify(0, builder.build());
                break;
            }
            case DetectedActivity.TILTING: {
                Log.e("ActivityRecogition", "Tilting: " + activity.getConfidence());
                break;
            }
            case DetectedActivity.WALKING: {
                Log.e("ActivityRecogition", "Walking: " + activity.getConfidence());
                break;
            }
            case DetectedActivity.UNKNOWN: {
                Log.e("ActivityRecogition", "Unknown: " + activity.getConfidence());
                break;
            }
        }
    }
}

首先,我使用了此链接中使用的API:http://code.tutsplus.com/tutorials/how-to-recognize-user-activity-with-activity-recognition--cms-25851

1 个答案:

答案 0 :(得分:4)

在AdnroidManifest.xml中添加必要的权限:

<uses-permission android:name = "android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

然后,您需要将引导消息与特定的BroadcastReceiver链接,该接收将处理并处理手机发出的消息(“boot”)。您可以将广播接收器定义为WakefulBroadcastReceiver的扩展,以确保设备在您的服务启动之前保持清醒,例如。

public class MyBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
  public void onReceive(Context con, Intent i) {
    Intent intent = new Intent(con, MyIntentService.class);
    startWakefulService(con, intent);
  }
}

之后,在清单文件中声明此接收器:

<receiver android:name="com.example.MyBroadcastReceiver">  
  <intent-filter>  
    <action android:name="android.intent.action.BOOT_COMPLETED" />  
  </intent-filter>  
</receiver>

BOOT_COMPLETED消息确保我们的接收器在设备启动时启动。当接收到引导消息时,“唤醒”接收器启动该服务。此外,我们需要在onHandleIntent中释放唤醒锁,以便设备在启动服务后重新进入休眠状态:

public class MyIntentService extends IntentService {
  @Override
  protected void onHandleIntent(Intent i) {
    //Release the wake lock
    WakefulBroadcastReceiver.completeWakefulIntent(i);
  } 
}

现在,只要设备启动,服务就会自动启动