我有一个服务,它有一个从布局xml文件中膨胀的按钮。我正在尝试向按钮添加onclicklistener,但由于某种原因,点击没有在按钮上正确注册。以下是扩展布局文件的服务代码。
public class OverlayServiceLayout extends Service implements View.OnClickListener
{
private WindowManager windowManager;
private LayoutInflater layoutInflater;
private RelativeLayout mTopView;
private Button myButton;
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "onservicelayout creation", Toast.LENGTH_SHORT).show();
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
PixelFormat.TRANSLUCENT
);
windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
mTopView = (RelativeLayout) layoutInflater.inflate(R.layout.service_main, null);
windowManager.addView(mTopView, params);
myButton = (Button) mTopView.findViewById(R.id.button);
myButton.setText("Button's text was changed");
myButton.setOnClickListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this, "on destroy was called", Toast.LENGTH_SHORT).show();
if(mTopView != null)
{
//Toast.makeText(this, "button is not null", Toast.LENGTH_SHORT).show();
try{
windowManager.removeView(mTopView);
}
catch(Exception ex)
{
ex.printStackTrace();
}
mTopView = null;
}
else
{
Toast.makeText(this, "button is null", Toast.LENGTH_SHORT).show();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onClick(View view)
{
Toast.makeText(this, "onclickregistered", Toast.LENGTH_SHORT).show();
/*
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", "Hi");
intent.putExtra(Intent.EXTRA_STREAM, R.drawable.smile);
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Send"));
*/
}
}
此处还有xml布局文件。它只是一个带按钮的相对布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="118dp"
android:layout_marginStart="118dp"
android:layout_marginTop="127dp" />
</RelativeLayout>
答案 0 :(得分:1)
您无法对服务中的视图进行通知,因为它们永远不会显示在屏幕上。如果服务需要来自用户的输入,它应该启动一个活动,然后可以创建用户可以与之交互的UI元素。