每个人。我正在尝试创建一个简单的应用程序来统计按钮被按下的次数。我正在尝试使用后台服务来执行此操作。该应用程序应计算“Press Me!”的次数被点击并在以吐司形式点击退出按钮时显示该数字。它运行,但它不显示buuton点击次数。我的代码如下:测量Android应用程序中点击按钮的次数
public class MainActivity extends Activity {
Button buttonStop, press;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStop = (Button) findViewById(R.id.buttonStop);
press = (Button) findViewById(R.id.buttonpress);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonpress:
Toast.makeText(MainActivity.this, "Service has started", Toast.LENGTH_SHORT).show();
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
finish();
break;
}
}
public class MyService extends Service {
int count= 0;
MainActivity main;
/**
* @see android.app.Service#onBind(Intent)
*/
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Number of times this button was pressed = " + count, Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
count = count +1 ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:id="@+id/buttonStop">
</Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me!"
android:id="@+id/buttonpress">
</Button>
</LinearLayout>
我也想获得日期,时间,纬度和经度,每次用户使用应用程序。请有人帮助我吗?这是我第一次建立服务,任何帮助将不胜感激。
出于好奇,你为什么要使用服务?或者仅仅是为了获得创建服务的体验? – 2011-03-01 06:14:50
什么时候应该创建服务,点击''按下我! '按钮或创建活动? – 2011-03-01 06:19:41
@Engprof:Java代码中的按钮在哪里? – Mudassir 2011-03-01 06:21:06