2

我正在尝试生成一些日志并在单击电源按钮后在屏幕上举杯。但这似乎不起作用。这是代码:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.pbtest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.ACTION_SHUTDOWN" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.test.pbtest.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name="com.test.pbtest.MyReceiver">
        <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF"></action>
            <action android:name="android.intent.action.SCREEN_ON"></action>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
            <action android:name="android.intent.action.ACTION_SHUTDOWN"></action>          
        </intent-filter>
    </receiver>        
</application>

</manifest>

MyReceiver.java 类:

package com.test.pbtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

    @Override
public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    Log.v("Hurray!", "Power button was clicked!");
        Toast.makeText(arg0, "power button clicked",Toast.LENGTH_LONG).show();
}

}

MainActivity.java 类:

package com.test.pbtest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

据我所知,我不需要显式注册我的接收器,因为我已经在清单文件中使用了它。请指导我哪里出错了。

4

2 回答 2

0

出于某种原因,您必须在运行时注册您的接收器..您可以通过服务注册它

于 2013-07-10T10:27:17.750 回答
0

您需要ACTION_SHUTDOWN在 AndroidManifest.xml 中添加权限:

 <uses-permission android:name="android.permission.ACTION_SHUTDOWN" />
于 2013-01-24T07:44:02.940 回答