Android之Service服务实现音乐播放器

Service四大组件之一 没有界面的组件,类似于Window中服务,是android中最重要的组件之一。
Service的实现方式:
继承android.app.service
生命周期:onCreate(只会执行一次)
onStartCoommand(非绑定进入,独立运行)
onDestroy
onBind(绑定,直接进入onBind)
onUnbind
非绑定:如音乐,定位
两种启动方式及区别:
Start:启动服务
Bind:绑定服务
开发步骤:
继承Service
注册Service
在android组件中启动Service
停止服务

public class MainActivity extends Activity {
    private Button strat1,strat2,strat3;
    private Button stop,stop2;
    private Button download,APK;
    private MyService myService;

    private ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService=((MyService.MyBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        strat1= (Button) findViewById(R.id.strat1);
        strat2= (Button) findViewById(R.id.strat2);
        strat3= (Button) findViewById(R.id.strat3);
        stop=(Button)findViewById(R.id.stop);
        stop2=(Button)findViewById(R.id.stop2);
        download=(Button)findViewById(R.id.download);
        APK=(Button)findViewById(R.id.APKcheck);
       strat1.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Intent it=new Intent(MainActivity.this,MyService.class);
               startService(it);
           }
       });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it=new Intent(MainActivity.this,MyService.class);
                stopService(it);
            }
        });
        //绑定
        strat2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,MyService.class);
               bindService(intent,serviceConnection,BIND_AUTO_CREATE);

            }
        });
        strat3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myService !=null){
                    myService.playMusic();
                }
            }
        });
        stop2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(serviceConnection);
            }
        });
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it=new Intent(MainActivity.this,DownService.class);
                startService(it);
            }
        });
        APK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it=new Intent(MainActivity.this,DownService.class);
                stopService(it);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

下面是Service服务的信息,Service服务可以实现异步任务类等;
同时需要注意是绑定与非绑定,以及回调的使用

public class DownService extends Service {
    private JSONObject jo;
    private int apk;
    private DownloadManager.Request request;
    private DownloadManager downloadManager;
    private Long ids;

    public DownService() {
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url= UrlUtil.ROOT_URL+"apk";
        new getFile().execute(url);
        return START_REDELIVER_INTENT;

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        downloadManager.remove(ids);

    }

    public void downLoad(){
        downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
        String downUrl=UrlUtil.ROOT_URL+"apk/cc.apk";
        request=
                new DownloadManager.Request(Uri.parse(downUrl));
        request.setDestinationInExternalPublicDir("/" + getPackageName() + "/", "aa.apk");
        request.setTitle("...下载");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        ids=downloadManager.enqueue(request);
        //异步任务类取消
//        getFile g=new getFile();
//        g.execute();
//        g.cancel(true);

    }

    public class getFile extends AsyncTask {

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.HttpGet(params[0]);
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.d("==o==", s);
            try {
                jo = new JSONObject(s);
                apk = jo.getInt("vid");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            int vid = 0;
            try {
                vid = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (apk > vid) {
                downLoad();
            }else{
                Toast.makeText(getBaseContext(), "已经是最新版本", Toast.LENGTH_SHORT).show();
            }

        }

    }
}
效果图:

Android之Service服务实现音乐播放器_第1张图片

你可能感兴趣的:(Android-前端,栀未央Android)