如何在服务中放置一个onclick监听器

时间:2012-12-20 06:27:25

标签: android service onclick onclicklistener android-notifications

我尝试将此onClick侦听器放入服务中,以便在通知栏内的自定义button视图中注册来自xml的点击。但是onClickListener会出现编译错误。有谁知道为什么会出现编译错误?

   RemoteViews remoteviews = new RemoteViews("com.example.test", R.layout.custom_notifications);

     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(AudioService.this)
               .setContent(remoteviews)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("My notification")
                .setContentText("Hello World!")
                .setOngoing(true);



     remoteviews.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

        Toast.makeText(AudioViewer.this, "play button was clicked", Toast.LENGTH_LONG).show();
            }
        });

编译器的错误如下图所示:

enter image description here

1 个答案:

答案 0 :(得分:7)

您需要使用setOnClickPendingIntent代替。 RemoteViews类没有定义setOnClickListener方法。

你需要做这样的事情:

this.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Toast.makeText(AudioViewer.this,
                        "play button was clicked", Toast.LENGTH_LONG).show();
                }
            }, new IntentFilter("MyRemoteViewsBroadcast"));
PendingIntent pi = PendingIntent.getBroadcast(this, 0,
                       new Intent("MyRemoteViewsBroadcast"), 0);
remoteviews.setOnClickPendingIntent(R.layout.custom_notifications, pi);