2011-03-01 77 views
0

每个人。我正在尝试创建一个简单的应用程序来统计按钮被按下的次数。我正在尝试使用后台服务来执行此操作。该应用程序应计算“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> 

我也想获得日期,时间,纬度和经度,每次用户使用应用程序。请有人帮助我吗?这是我第一次建立服务,任何帮助将不胜感激。

+0

出于好奇,你为什么要使用服务?或者仅仅是为了获得创建服务的体验? – 2011-03-01 06:14:50

+0

什么时候应该创建服务,点击''按下我! '按钮或创建活动? – 2011-03-01 06:19:41

+0

@Engprof:Java代码中的按钮在哪里? – Mudassir 2011-03-01 06:21:06

回答

0

要确保显示Toast消息,请按Exit按钮单击而不是onDestroy

1

你快到了!

三件事情忘了做:

  • 让你的MainActivity实施View.OnClickListener - 如果你在你的onClick()方法,编译器会一直放倒你离开之前使用@Override。一般来说,无论您何时实现一个您期望框架调用的函数,都可以使用@Override作为完整性检查。

  • 附上您的MainActivity到你的按钮使用View.setOnClickListener() - 这实际上告诉按钮来调用你的onClick()方法是单击时。

  • (可能)在您的元素中定义您的服务在您的AndroidManifest.xml - 棒<service android:name="MyService"/>。如果你没有这样做,你可以通过查看Logcat找到(DDMS或Debug透视图)。它会一直说:

无法启动服务的意图[...]:找不到

这就是我曾在你的代码更改,然后祝酒词出现了在我的屏幕上点击适当的点击数。