Android多媒体__信息和简单的音乐播放

原创 2016年05月31日 21:56:13
接收和发送短信的功能

public class MainActivity extends Activity {

    //receive
    private TextView sender;
    private TextView content;

    private IntentFilter receFilter;
    private MessagerReceiver messagerReceiver;


    //send
    private EditText msgInput;
    private EditText to;
    private Button send;


    //监控
    private IntentFilter sendFilter;
    private SendStatusReceiver sendStatusReceiver;


    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        //recieve
        sender =(TextView)findViewById(R.id.sender);
        content  =(TextView)findViewById(R.id.content);

        //动态注册广播
        receFilter = new IntentFilter();
        receFilter.addAction("android.provider.Telephony.SMS_RECEIVED");


        messagerReceiver = new MessagerReceiver();
        //注册广播
        registerReceiver(messagerReceiver, receFilter);


        //send
        to = (EditText)findViewById(R.id.to);
        msgInput = (EditText)findViewById(R.id.msgInput);

        send = (Button)findViewById(R.id.send_button);


        //监控,发送是否成功,利用广播
        sendFilter = new IntentFilter();
        sendFilter.addAction("SENT_SMS_ACTION");
        sendStatusReceiver = new SendStatusReceiver();
        //注册广播
        registerReceiver(sendStatusReceiver, sendFilter);


        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SmsManager smsManager = SmsManager.getDefault();
                Intent sendIntent = new Intent("SENT_SMS_ACTION");
                PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, sendIntent, 0);

                smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null);
            }
        });


    }

    protected void onDestroy(){
        //活动退出的时候取消注册
        super.onDestroy();
        unregisterReceiver(messagerReceiver);
    }

    class MessagerReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            //Bundle 
            Bundle bundle = intent.getExtras();

            //提取短信信息
            Object[] pdus = (Object[])bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];

            for(int i=0;i<messages.length;i++){
                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            }

            String address = messages[0].getOriginatingAddress();

            String fullMessage = "";

            for(SmsMessage message : messages){
                fullMessage+=message.getMessageBody();
            }
            sender.setText(address);
            content.setText(fullMessage);
        }

    }

    class SendStatusReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if(getResultCode() == RESULT_OK){
                Toast.makeText(context, "send success", Toast.LENGTH_SHORT).show();

            }else{
                Toast.makeText(context, "send failed", Toast.LENGTH_SHORT).show();
            }
        }

    }

}


main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="50dp">

         <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:padding="10dp"
            android:text="From:"/>

         <TextView 
             android:id="@+id/sender"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center_vertical"
             />


    </LinearLayout>


    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:padding="10dp"
            android:text="Content:"/>

        <TextView 
            android:id="@+id/content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"/>
    </LinearLayout>


    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:layout_gravity="center_vertical"
            android:textSize="20sp"
            android:text="To:"/>
        <EditText 
            android:id="@+id/to"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:layout_weight="1"/>
    </LinearLayout>


    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="50dp"
        >

        <EditText
            android:id="@+id/msgInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            android:textSize="20sp"
            />
             <Button 
             android:id="@+id/send_button"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="Send"/>
    </LinearLayout>





</LinearLayout>


权限
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
   <uses-permission android:name="android.permission.SEND_SMS"/>


 调用拍照和图片裁减:
 public class MainActivity extends Activity {

    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int CHOOSE_PHOTO=3;


    private Button chooseFromAlbm;
    private Button takePhoto;
    private ImageView image;

    private Uri imageUri;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        takePhoto = (Button)findViewById(R.id.take_photo);
        image = (ImageView)findViewById(R.id.image);

        takePhoto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //首先先创建文件流存储照片
                File outputImage = new File(Environment.getExternalStorageDirectory(),
                        "output_image.jpg");

                try {
                    if(outputImage.exists()){

                        outputImage.delete();

                    }else{

                        outputImage.createNewFile();
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                //获取imageUri
                imageUri = Uri.fromFile(outputImage);

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                startActivityForResult(intent, TAKE_PHOTO);//打开相机
            }
        });

        chooseFromAlbm = (Button)findViewById(R.id.choose_button);
        chooseFromAlbm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent("android.intent.action.GET_CONTENT");

                intent.setType("image/*");
                startActivityForResult(intent, CHOOSE_PHOTO);
            }
        });

    }


    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        switch(requestCode){
        case TAKE_PHOTO:

            Intent intent = new Intent("com.android.camera.action.CROP");
            //System.out.println( data.getStringExtra(MediaStore.EXTRA_OUTPUT));
//          System.out.println(data.getDataString());
            intent.setDataAndType(imageUri, "image/*");
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, CROP_PHOTO);
            break;
        case CROP_PHOTO:
            if(resultCode==RESULT_OK){
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                            .openInputStream(imageUri));
                    //将裁减后的图片显示出来
                    image.setImageBitmap(bitmap);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            break;

        case CHOOSE_PHOTO:
            if(resultCode==RESULT_OK){
                if(Build.VERSION.SDK_INT>=19){
                    handleImageOnKitKat(data);
                }else{
                    handleImageBeforeKitKat(data);
                }
            }
            break;
        default:
            break;
        }
    }


    @TargetApi(19) 
    private void handleImageOnKitKat(Intent data) {
        // TODO Auto-generated method stub
        String imagePath = null;
        Uri uri = data.getData();
//      Log.d("uri", uri.toString());
//      Log.d("uri2", uri.getScheme().toString());
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".
                    equals(uri.getAuthority())){

                String id = docId.split(":")[1];//解析出数字id
                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);

            }else if("com.android.providers.downloads.documents"
                    .equals(uri.getAuthority())){
                Uri contentUri = ContentUris.
                        withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));

                imagePath = getImagePath(contentUri,null);
            }


        }else if("content".equalsIgnoreCase(uri.getScheme())){

            imagePath =getImagePath(uri,null);

        }

        displayImage(imagePath);


    }


    private void displayImage(String imagePath) {
        // TODO Auto-generated method stub
//      imagePath = "/mnt/sdcard/DCIM/Camera/bcd.jpg";
        if(imagePath!=null){

            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            Log.d("imagePath", imagePath);
            //图片太大会加载不了,卧槽
            image.setImageBitmap(bitmap);

        }else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }


    private void handleImageBeforeKitKat(Intent data) {
        // TODO Auto-generated method stub
        Uri uri = data.getData();

        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }


    private String getImagePath(Uri uri, String selection) {
        // TODO Auto-generated method stub

        String path = null;
        Cursor cursor = getContentResolver().query(uri, 
                null, selection, null, null);
        if(cursor!=null){

        if(cursor.moveToFirst()){
            path = cursor.getString(cursor.getColumnIndex(Media.DATA));
        }
        cursor.close();

        }
        return path;
    }
}


main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button 
        android:id="@+id/take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo"/>

    <Button 
        android:id="@+id/choose_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose From Albm"/>

    <ImageView 
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>


</LinearLayout>


权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>



MP3播放:
public class MainActivity extends Activity implements OnClickListener {

    private Button play;
    private Button pause;
    private Button stop;
    private MediaPlayer mediaPlayer = new MediaPlayer();

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

        play = (Button) findViewById(R.id.play_button);
        pause = (Button) findViewById(R.id.pause_button);
        stop = (Button) findViewById(R.id.stop_button);

        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.setOnClickListener(this);

        initMediaPlayer();
    }

    private void initMediaPlayer() {
        // TODO Auto-generated method stub
        try {
            File file = new File(Environment.getExternalStorageDirectory(),
                    "music.mp3");
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.play_button:
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
            break;
        case R.id.pause_button:
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();

            }
            break;
        case R.id.stop_button:
            if (mediaPlayer.isPlaying()) {
                //音乐文件重置再初始化
                mediaPlayer.reset();
                initMediaPlayer();
                //对于视频来说就是
                //VideoView videoView 
                //videoView.resume();
            }
            break;
        default:
            break;
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            //videoView.suspend();
        }
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

Android 多媒体开发学习之简单的音乐播放器

我们今天的目的是学习如何创建一个简单的音乐播放器,可支持播放,暂停,继续播放,以及进度显示,已经进度拖拽。 既然我们的目的已经很明确,那我们先分析一下: 1: 我们播放音乐的任务可以放在Activ...

Android之多媒体MediaPlayer(一个简单的音乐播放器)

音乐播放器MediaPlayer: 利用Environment.getExternalStorageDirectory()方法得到sdcard路径,然后用new File(得到的sdcard...

Android多媒体学习六:利用Service实现背景音乐的播放

Android允许我们使用Service组件来完成后台任务,这些任务的允许不会影响到用户其他的交互。 1、Activity类package demo.camera; import android.a...

Android多媒体编程——MediaPlayer播放音乐

Android多媒体——使用MediaPlayer播放声音 API 在我们的项目中经常会遇到播放声音的功能,在Android中系统的framework已经提供了调用播放声音的API——Medi...

Android Media(多媒体)获取手机内存卡下的音乐并播放

代码实现: package com.example.g160628_android_27_media; import android.media.AudioManager; import ...

android开发笔记之多媒体—播放音频(音乐)

Android应用增加动画,视频,音乐等多媒体功能,因此为手机提供音频录制,播放,视频录制,播放的功能十分重要。Android提供了常见音频,视频的编码,解码机制,Android支持的音频格式有MP3...

【android学习之十四】——多媒体1:音乐播放

声明:学习的书籍《Android应用开发揭秘》,这里记录学习该书籍的日志,引用的相关代码与总结描述,没有商业的用途,完全是自我学习的一个记录,刚刚学习不可避免会出现很多问题,若是有错误还请大家多多批评...

Android多媒体学习六:利用Service实现背景音乐的播放

Android允许我们使用Service组件来完成后台任务,这些任务的允许不会影响到用户其他的交互。   1、Activity类 [java] view plain copy ...
  • dddxxxx
  • dddxxxx
  • 2016年09月06日 12:02
  • 430

android 多媒体之播放网络音乐demo

android 多媒体之播放网络音乐demo 需要用到Tomcat服务器 用到的类有Mediapalyer,Uri等 代码如下: packa...

Android Activity与Service交互,startservice,bindService多媒体播放器音乐播放暂停按钮请求服务设置按钮图片问题

偶遇音乐播放器按钮设置图片响应事件监听,请求服务时出现异常,不能暂停播放歌曲,请且播放按钮的图片不能转变 经调试发现,因为请求了服务端service的对应接口的方法两次,造成参数没发生变化,再点击音...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android多媒体__信息和简单的音乐播放
举报原因:
原因补充:

(最多只允许输入30个字)