How to Obtain Service instance, do not aidl

public class MainActivity extends AppCompatActivity {


    MyService myService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // 启动service
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
// 获取service例子
        myService = MyService.getRxMqtt();
    }

    public  void  methodService(View view){
  // 不通aidl调用service方法
        myService.publish("topic1110","msg100");

    }
}


public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public  void publish(final String topic, final String msg) {

        Log.e("denganzhi1","topic:"+topic+"msg:"+msg);
        Toast.makeText(getApplicationContext(),"service...",Toast.LENGTH_SHORT).show();

    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("denganzhi1","service启动");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("denganzhi1","MyService--》destory");
    }

    private static MyService rxMqtt;
    /**
     * 单例获取实例
     */
    public static MyService getRxMqtt() {
        if (rxMqtt == null) {
            synchronized (MyService.class) {
                if (rxMqtt == null) {
                    rxMqtt = new MyService();
                }
            }

        }
        return rxMqtt;
    }

}

 

Published 141 original articles · won praise 51 · views 90000 +

Guess you like

Origin blog.csdn.net/dreams_deng/article/details/88988100