如何在android-java中同时扩展Activity类和BroadcastReceiver

时间:2016-05-22 16:56:07

标签: java android android-intent android-broadcastreceiver

我播放了一个意图:com.ss.CUSTOM_INTENT

/*-----Class BroadcastReceiverApp-------*/<br/>
public class BroadcastReceiverApp extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.broadcast_activity);
    }

/*    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }*/

    // broadcast a custom intent.
    public void broadcastIntent(View view){
        Intent intent = new Intent();
        intent.setAction("com.ss.CUSTOM_INTENT");
        sendBroadcast(intent);
    }
}
/*------------------------*/

但是当我收到广播意图时,我希望它在通知抽屉中显示。 Receiver类只能扩展BroadcastReceiver类,因此它现在允许在那里扩展Activity类,我不能使用:

Context context = getApplicationContext();

将在Notification.Builder(context)中进一步使用....

这是我的广播接收器课程:

public class MyReceiver extends BroadcastReceiver , Activity{

    private static final int MY_NOTIFICATION_ID=1;
    NotificationManager notificationManager;
    Notification myNotification;
    private final String myBlog = "http://android-er.blogspot.com/";
    Context cont = getApplicationContext();

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();

                Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
        PendingIntent pendingIntent = PendingIntent.getActivity(
                MyReceiver.this,
                0,
                myIntent,
                Intent.FLAG_ACTIVITY_NEW_TASK);

        myNotification = new Notification.Builder(context)
                .setContentTitle("Exercise of Notification!")
                .setContentText("http://android-er.blogspot.com/")
                .setTicker("Notification!")
                .setWhen(System.currentTimeMillis())
                .setContentIntent(pendingIntent)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_launcher)
                .build();

        notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

        Log.i(getClass().getSimpleName(),"Sucessfully Changed Time");
    }
}

有人可以帮忙吗?我想稍后将广播意图更改为“android.intent.action.DATE_CHANGED / TIME_CHANGED”,这甚至无效。

1 个答案:

答案 0 :(得分:1)

  

但是当我收到广播意图时,我希望它是   通知抽屉中显示。

如果您的问题是&#34;如何从BroadcastReceiver更新gui&#34;您必须将BroadcastReceiver类放在要更新的Activity中。

嵌套的BroadcastReceiver类可以访问外部Activity的元素。

举个例子见 Android BroadcastReceiver within Activity