Service IntentService Android中的线程 MediaPlayer

在Service中添加线程

注意服务是需要注册的
Service IntentService Android中的线程 MediaPlayer_第1张图片

public class MyService extends Service {
    private int count;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("", "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("","onStartCommand");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count<100){
                    count++;
                    Intent intent = new Intent();
                    intent.setAction(MainActivity.DOWN_LOAD_ACTION);
                    intent.putExtra("count", count);
                    sendBroadcast(intent);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("", "onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
public class MainActivity extends Activity implements View.OnClickListener {
    public static final String DOWN_LOAD_ACTION ="com.service.test" ;
    private ProgressBar mProgressbar;
    private Button mButtonDownload;
    private Button mButtonStop;
    private MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DOWN_LOAD_ACTION);
        registerReceiver(myReceiver, filter);

        mProgressbar = (ProgressBar) findViewById(R.id.progressbar_download);
        mProgressbar.setOnClickListener(this);
        mButtonDownload = (Button) findViewById(R.id.button_download);
        mButtonStop = (Button) findViewById(R.id.button_stop);
        mButtonDownload.setOnClickListener(this);
        mButtonStop.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button_stop:
                Intent intent1 = new Intent(getApplicationContext(),MyIntentService.class);
                stopService(intent1);
                break;
            case R.id.button_download:
                Intent intent = new Intent(getApplicationContext(),MyIntentService.class);
                startService(intent);
                break;
            default:
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int count = intent.getIntExtra("count",0);
            mProgressbar.setProgress(count);
        }
    }
}

利用IntentService添加线程,因为其自身包含一个线程,所以不用new Thread一个线程

public class MyIntentService extends IntentService {
    private int count;
    public MyIntentService(String name) {
        super(name);//调用父类的有参构造函数
    }
    public MyIntentService(){
        this("");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService","服务关闭");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("MyIntentService","运行到IntentService");
        while (true){
            if (count>100){
                count=0;
            }
            count++;
            Intent intent2 = new Intent();
            intent2.setAction(MainActivity.DOWN_LOAD_ACTION);
            intent2.putExtra("count", count);
            sendBroadcast(intent2);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Android中的进程、线程

加入新的进程有两种方法handler asynctask

handler

子线程给主线程发消息

方法一:

public class MainActivity extends Activity {
    private Button mButton;
    private int count = 60;
    public static final int TIME_DESC =0x23 ;
    private MyHandler handler = new MyHandler();
    class MyHandler extends Handler{

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case TIME_DESC:
                    count--;
                    mButton.setText(count+"秒");
                    if (count>0){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.sendEmptyMessage(TIME_DESC);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                count = 60;
                handler.sendEmptyMessage(TIME_DESC);
            }
        });
    }
}

方法二:

public class MainActivity extends Activity {
    private Button mButton;
    private int count = 60;
    public static final int TIME_DESC =0x23 ;
    private MyHandler handler = new MyHandler();
    class MyHandler extends Handler{

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case TIME_DESC:

                    String time = (String) msg.obj;
                    mButton.setText(time);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                count = 60;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (count>0){
                            count--;
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message msg = new Message();
                            msg.obj = count+"秒";
                            msg.what = TIEM_DESC;
                            handler.sendMessage(msg);
                        }

                    }
                }).start();
            }
        });
    }   
}

主线程给子线程发消息

基本不这么用,

public class MainActivity extends Activity {
    private Button mButton;
    private Button mButton2;
    private int count = 60;
    public static final int TIME_DESC =0x23 ;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button);
        mButton2 = (Button) findViewById(R.id.button2);
        mButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.sendEmptyMessage(0);
            }
        });
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                count = 60;
                MyThread thread = new MyThread();
                thread.start();

            }
        });
    }

    class MyThread extends Thread{
        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    Log.d("handler","接受主线程的消息");
                    super.handleMessage(msg);
                }
            };
            Looper.loop();
        }
    }
}

AsyncTask

public class MainActivity extends Activity {
    private Button mButton;
    private ProgressBar mProgressbar;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button);
        mProgressbar = (ProgressBar) findViewById(R.id.progressbar);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyTast tast = new MyTast();
                tast.execute("去执行");//用execute()方法调用
            }
        });
    }
    class MyTast extends AsyncTask{
        @Override
        protected void onPostExecute(String s) {//运行结束
            super.onPostExecute(s);
            mButton.setText(s);
        }

        @Override
        protected void onProgressUpdate(String... values) {//中间运行
            super.onProgressUpdate(values);
            int count = Integer.parseInt(values[0]);
            mProgressbar.setProgress(count);
        }

        @Override
        protected String doInBackground(String... strings) {//开始运行
            while (count<101){
                count++;
                publishProgress(""+count);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("",""+count);
            }
            return "执行结束";//返回onPostExecute 中的s值
        }
    }
}

MediaPlayer

public class MainActivity extends Activity {
    private Button mButtonStartMusic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonStartMusic = (Button) findViewById(R.id.button_music);
        mButtonStartMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MediaPlayer mediaPlayer = new MediaPlayer();
                mediaPlayer.reset();
                Log.d("","文件路径"+Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC));
                File musicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
                File[] files = musicDir.listFiles();
                try {
                    mediaPlayer.setDataSource(files[0].getAbsolutePath());
                    mediaPlayer.prepare();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.start();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


}

你可能感兴趣的:(mediaplayer,线程,handler,looper,记录)