我创建了一个带有3个标签(片段)的应用程序,在第一个片段中,我尝试使用api,但没有任何效果,如果我在mainactivity中编写api的代码,它工作正常。我在这做错了什么?我在android studio中没有错误!
这是片段
的代码public class Tab1Stepcounter extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1stepcounter, container, false);
return rootView;
}
protected class Stepcounter extends AppCompatActivity implements
OnDataPointListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
{
private static final int REQUEST_OAUTH = 1;
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;
private GoogleApiClient mApiClient;
private ProgressBar progressBar;
private int progressStatus=0;
private Handler handler= new Handler();
private TextView textView;
private Button toastButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1stepcounter);
if (savedInstanceState != null){
authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
}
mApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
toastButton = (Button) findViewById(R.id.show_toast);
progressBar = (ProgressBar) findViewById(R.id.progressBar3);
}
@Override
protected void onStart(){
super.onStart();
mApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
.setDataTypes( DataType.TYPE_STEP_COUNT_CUMULATIVE )
.setDataSourceTypes( DataSource.TYPE_RAW )
.build();
ResultCallback<DataSourcesResult> dataSourcesResultCallback = new ResultCallback<DataSourcesResult>() {
@Override
public void onResult(DataSourcesResult dataSourcesResult) {
for( DataSource dataSource : dataSourcesResult.getDataSources() ) {
if( DataType.TYPE_STEP_COUNT_CUMULATIVE.equals( dataSource.getDataType() ) ) {
registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_CUMULATIVE);
}
}
}
};
Fitness.SensorsApi.findDataSources(mApiClient, dataSourceRequest)
.setResultCallback(dataSourcesResultCallback);
}
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {
SensorRequest request = new SensorRequest.Builder()
.setDataSource( dataSource )
.setDataType( dataType )
.setSamplingRate( 3, TimeUnit.SECONDS )
.build();
Fitness.SensorsApi.add( mApiClient, request, this )
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e( "GoogleFit", "SensorApi successfully added" );
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(!authInProgress){
try{
authInProgress = true;
connectionResult.startResolutionForResult( Stepcounter.this,REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e){}
}else {
Log.e( "GoogleFit" , "authInProgress" );
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_OAUTH ) {
authInProgress = false;
if( resultCode == RESULT_OK ) {
if( !mApiClient.isConnecting() && !mApiClient.isConnected() ) {
mApiClient.connect();
}
} else if( resultCode == RESULT_CANCELED ) {
Log.e( "GoogleFit", "RESULT_CANCELED" );
}
} else {
Log.e("GoogleFit", "requestCode NOT request_oauth");
}
}
@Override
public void onDataPoint(DataPoint dataPoint) {
for( final Field field : dataPoint.getDataType().getFields() ) {
final Value value = dataPoint.getValue( field );
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), field.getName() + " : " + value, Toast.LENGTH_SHORT).show();
textView = (TextView) findViewById(R.id.textView);
textView.setText(field.getName()+ ": " + value);
textView = (TextView) findViewById(R.id.textView);
progressStatus = value.asInt();
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
});
toastButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Toast.makeText(getApplicationContext(), field.getName() + " : " + value, Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
protected void onStop() {
super.onStop();
Fitness.SensorsApi.remove( mApiClient, this )
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
mApiClient.disconnect();
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(AUTH_PENDING, authInProgress);
}
}
}
以下是代码表格主要活动
public class MainActivity extends AppCompatActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Stepcounter tab1 = new Tab1Stepcounter();
return tab1;
case 1:
Tab2History tab2 = new Tab2History();
return tab2;
case 2:
Tab3Sesions tab3 = new Tab3Sesions();
return tab3;
default:
return null;
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Step Counter";
case 1:
return "History";
case 2:
return "Sesions";
}
return null;
}
}
}
答案 0 :(得分:0)
我认为您的Stepcounter
活动未启动,因此未调用API。您有几个选择来解决这个问题:
重构代码,以便您的Tab1Stepcounter负责启动API。
将API逻辑移至MainActivity。
从Tab1Stepcounter片段中启动Stepcounter活动(您的onCreateView()
只会让视图膨胀,但不会启动活动。)