如何检查从Android广播接收器收到的动作类型?

时间:2017-01-11 07:28:27

标签: android

我目前正在研究Android中的广播接收器,我不知道如何检查Broad Cast接收器中调用的动作类型。下面是我的清单文件和java文件:

android manifest:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:typeface="serif">
    <receiver android:name=".Main2Activity">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        </intent-filter>
    </receiver>
</application>

Java文件:

package com.example.ashis.assignment1;

public class Main2Activity extends BroadcastReceiver {

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

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Wallpaper has been changed......", Toast.LENGTH_LONG).show();
    }
}

是否可以检查我的Main2Activity.java文件中清单文件中描述的操作类型?

4 个答案:

答案 0 :(得分:2)

由于以下代码是您要添加的清单中的清单

intent.getAction()

您可以使用public class Main2Activity extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String message = ""; switch (intent.getAction()) { case Intent.ACTION_POWER_CONNECTED: message = "Power Connected"; break; case Intent.ACTION_POWER_DISCONNECTED: message = "Power Disconnected"; break; } Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } } 来检查发生了什么类型的操作:

{{1}}

答案 1 :(得分:1)

在你的onReceive()方法中

@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
 if(action.equals("android.intent.action.ACTION_POWER_CONNECTED")){

   Toast.makeText(context,"action",Toast.LENGTH_LONG).show();
   }
}

答案 2 :(得分:0)

这很简单:

String action = intent.getAction();

答案 3 :(得分:-1)

试试这个

<receiver android:name=".PowerStatusReceiver ">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
        </intent-filter>
    </receiver>

然后在[{1}}

onCreate中注册收件人
activity

定义我们的BroadcastReceiver并在其中嵌入BATTERY_STATUS请求

// register our power status receivers

    IntentFilter powerConnectedFilter = new IntentFilter(Intent.ACTION_POWER_CONNECTED);
    registerReceiver(PowerStatusReceiver , powerConnectedFilter);

    IntentFilter powerDisconnectedFilter = new IntentFilter(Intent.ACTION_POWER_DISCONNECTED);
    registerReceiver(PowerStatusReceiver , powerDisconnectedFilter);