我试图提供一项服务来识别用户的当前活动。 但是此代码每次都会崩溃。
它引发异常:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'com.google.android.gms.location.DetectedActivity com.google.android.gms.location.ActivityRecognitionResult.getMostProbableActivity()' 在com.always_in_beta.ecodrive.service.UserTrackService.detectActivity(UserTrackService.java:51) 在com.always_in_beta.ecodrive.service.UserTrackService $ 1.run(UserTrackService.java:27)
代码是:
public class UserTrackService extends Service {
public Handler handler = null;
public Runnable runnable = null;
int count = 0;
public Context context = this;
public Intent intentt;
@Override
public void onCreate() {
handler = new Handler();
runnable = new Runnable() {
public void run() {
detectActivity();
}
};
handler.postDelayed(runnable, 4000);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Toast.makeText(context, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
intentt = intent;
return null;
}
public void detectActivity() {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intentt);
DetectedActivity activity = result.getMostProbableActivity();
Toast.makeText(context, activity.toString(), Toast.LENGTH_SHORT).show();
Log.d("tag_tag_tag", activity.toString());
}
}
答案 0 :(得分:0)
ActivityRecognitionResult#extractResult(android.content.Intent)
返回 ActivityRecognitionResult,如果意图不成立,则为null 包含一个ActivityRecognitionResult。
因此,根据您的空指针堆栈跟踪,这是预料之中的,因为您无法在 null 上运行getMostProbableActivity()
。