无法从Activity或BroadcastReceiver停止服务

时间:2013-10-16 08:44:06

标签: android android-service

我有一个服务,显示一个浮动图标,显示应用程序的状态。但在某些时候我想通过停止服务来隐藏浮动图标。所以我有一个广播来处理,但问题是我无法通过调用context.stopService(new Intent(context, FloaticonService.class))来停止服务。

以下是BroadcastReceiver FloaticonReceiver.java

public class FloaticonReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            context.stopService(new Intent(context, FloaticonService.class));
    }
}

以下是服务代码FloaticonService.java

public class FloaticonService extends Service {

    private WindowManager windowManager;
    private ImageView floatIcon;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        floatIcon = new ImageView(this);
        floatIcon.setImageResource(R.drawable.ic_launcher);

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.TOP | Gravity.LEFT;
        params.x = 0;
        params.y = 100;

        windowManager.addView(floatIcon, params);

    }

}

2 个答案:

答案 0 :(得分:1)

试试这个

FloaticonService课程中添加此内容:

@Override
public void onDestroy() {
    super.onDestroy();
    windowManager.removeView(floatIcon);

}

希望它有所帮助。

答案 1 :(得分:0)

我像这样使用它和它的工作:

public class OnBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        final Intent mOnBootServiceIntent = new Intent(context, OnBootService.class);

        context.startService(OnBootServiceIntent);
     //or                        
        context.stopService(OnBootServiceIntent);

        Toast.makeText(context, "is active!", Toast.LENGTH_SHORT).show();
    }   
}