Android多媒體__信息和簡單的音樂播放

接收和發送短信的功能

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();
        }
    }
}
發佈了33 篇原創文章 · 獲贊 6 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章