手机关机时的Android广播接收器

时间:2013-12-20 16:54:43

标签: android broadcastreceiver

(对不起我的英语,我不会说得很好)

我是Android的佼佼者。所以我想用Android模拟器测试应用程序,该模拟器在控制台上显示一条消息,说明手机已关闭。

我关闭模拟器时,我所做的应用程序没有显示任何内容。

你能解释一下原因吗?

清单中的

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.broadcastreceiver.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.example.broadcastreceiver.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

Class Main

public class MainActivity extends Activity {

private BroadcastReceiver the_receiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context c, Intent i) {
                if(i.getAction().equals("android.intent.action.ACTION_SHUTDOWN")){
                     System.out.println("the phone is switched off");      
                 }
    }};

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

1 个答案:

答案 0 :(得分:0)

将您的BroadcastReceiver移至另一个班级。在您的清单中,您已将“com.example.broadcastreceiver.MainActivity”声明为ActivityBroadcastReceiver,但事实并非如此。它只是Activity。它不可能都是。