使用广播接收器打开电源按钮点击次数的app

时间:2013-01-24 07:34:06

标签: android broadcastreceiver

我正在尝试生成一些日志,并在电源按钮点击后在屏幕上显示吐司。 但它似乎没有用。这是代码:

的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;
    }

}

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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