我想做的就是用一个按钮启动wake_lock,然后用另一个按钮结束它。它可以在我正在创建的更大的应用程序中使用,但这是我一直遇到问题的部分。我查看了这个网站和其他网站,发现所有代码都完全相同,但它对我不起作用 -我做错了什么?
我的 Java 代码:
package com.example.tester_app;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class TestMain extends Activity {
PowerManager.WakeLock wl;
Button bstart, bstop;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView (R.layout.main);
//Views from xml
bstart = (Button) findViewById (R.id.bStart);
bstop = (Button) findViewById (R.id.bStop);
//power manager for wake lock..
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
bstart.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(TestMain.this, "started", Toast.LENGTH_SHORT).show();
wl.acquire(); //keeps cpu from sleeping
}
});
bstop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(TestMain.this, "stopped", Toast.LENGTH_SHORT).show();
wl.release();
}
});
}
}
我的 XML 代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/bStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
<Button
android:id="@+id/bStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Stop" />
</LinearLayout>
我的清单代码:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tester_app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WAKE_LOCK" ></uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Main"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>