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();
        }
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Haihao_micro/article/details/51549523

SQL Server 7.0数据库的六种数据移动方法

SQL Server 7.0数据库的六种数据移动方法转自:世纪易网 2003年3月3日20:6本人从事的工作是数据库管理员,要维护多台服务器中的数据库,经常把某台服务器中的某个数据库移动到另外一台服务...
  • howel
  • howel
  • 2003-04-30 11:15:00
  • 1253

最简单Android音乐播放器

Android在播放音频和视频方面提供了一套完整的API,可以轻松地编写出一个简单的音频播放器。         在 Android 中播放音频文件一般都是使用 MediaPlayer 类来实现的,...
  • u012796139
  • u012796139
  • 2015-11-23 10:21:18
  • 901

Android实现简单的音乐播放

android实现音乐播放效果,简单的服务开启。 这里将用到android的四大组件之一:Service 注意:Service是自大组件之一,需要注册。...
  • Json_Jerry
  • Json_Jerry
  • 2016-09-22 20:05:36
  • 9591

android 利用 service 实现音乐播放

android利用service实现音乐播放
  • zhao123h
  • zhao123h
  • 2014-06-22 21:51:30
  • 2947

notification+service+broadcastreceiver实现简单的音乐播放器

notification+service+broadcastreceiver实现简单的音乐播放器
  • u010032372
  • u010032372
  • 2015-04-14 15:26:45
  • 1193

Android 多媒体文件获取工具类

package com.android.ocr.util;import java.io.File; import java.util.ArrayList; import java.util.List;...
  • lovoo
  • lovoo
  • 2016-06-18 08:27:54
  • 1409

Android之MediaPlayer(多媒体之音乐播放)

本篇文章是对Android中MediaPlayer的使用方法进行了详细的分析介绍,需要的朋友可以参考下 1. 如何获得MediaPlayer实例: 可以使用直接new的方式: MediaPla...
  • suzhen666
  • suzhen666
  • 2017-02-19 18:52:44
  • 116

Android 音乐播放(多媒体)

Android 音乐播放(多媒体)
  • dzzzheng95
  • dzzzheng95
  • 2017-02-21 23:31:24
  • 115

Android开发学习之路--MediaPlayer之简单音乐播放器初体验

很多时候我们都会用手机来播放音乐,播放视频,那么具体地要怎么实现呢,其实主要是MediaPlayer类来完成的。下面通过简单的例子来实现一首歌曲的播放吧。新建工程MediaPlayerStudy,...
  • eastmoon502136
  • eastmoon502136
  • 2016-02-16 21:59:33
  • 4796

Android 三种简单版音乐播放器原理解析

读取raw文件夹下的音乐 1.音乐播放简单布局文件:     xmlns:tools="http://schemas.android.com/tools" android:id="@+id/act...
  • Cy_Camaro
  • Cy_Camaro
  • 2017-02-10 01:23:39
  • 722
收藏助手
不良信息举报
您举报文章:Android多媒体__信息和简单的音乐播放
举报原因:
原因补充:

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