如何从通知操作开始方法?

时间:2014-05-13 17:09:01

标签: android methods notifications android-activity broadcastreceiver

在我的主要课程中,我有一个notificationBuilder,它点击了按钮。

        NotificationManager NotifyMgr =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    PendingIntent turnOffIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(NotifiReceiver.turnOffFlash), 0);
    PendingIntent contentIntent = PendingIntent.getActivity(this,
            0, new Intent(this, MainActivity.class), 0);
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_lightbulb_on)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(getString(R.string.app_name))
                    .setContentIntent(contentIntent)
                    .setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(getString(R.string.app_name) + "dfddddddggffgf"))
                    .addAction(R.drawable.ic_lightbulb,
                            getString(R.string.app_name), turnOffIntent);
    NotifyMgr.notify(notificationId, builder.build());

这是NotifiReceiver.class

    package com.AleXMan.torch.standart;

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

public class NotifiReceiver extends BroadcastReceiver {

    MainActivity mna = new MainActivity();
    public static final String turnOffFlash = "com.AleXMan.torch.standart.turnOffFlash";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("test", "recieved");
        if (intent.getAction().equals(turnOffFlash)) {
            mna.toggleFrstFlash();
            Log.i("test", "confirmed");
        }
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

但是当我点击通知中的“按钮”时:.addAction(R.drawable.ic_lightbulb, getString(R.string.app_name), turnOffIntent); 没有任何反应 你能告诉我这里究竟做错了什么吗? 非常感谢,为了您将来的帮助!

1 个答案:

答案 0 :(得分:0)

鉴于您当前的代码,您需要将其作为清单中<application>元素的子代:

<receiver android:name="NotifiReceiver">
  <intent-filter>
    <action android:name="com.AleXMan.torch.standart.turnOffFlash" />
  </intent-filter>
</receiver>

但是,更好的方法是将new Intent(NotifiReceiver.turnOffFlash)替换为new Intent(this, NotifiReceiver.class)。然后,您可以:

<receiver android:name="NotifiReceiver"/>

减少打字和提高安全性。

请注意,这假设根package元素中的<manifest>com.AleXMan.torch.standart