系统组件主要类应用

一、简介

Android提供了很多可以使用的组件,例如震动,蓝牙,wifi等,下面是一些重要或者经常用到的类。

二、常用组件使用

1、震动Vibrator

Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);

vibrator.vibrate(50);

注意添加权限

 

2、播放音乐SoundPool

API21之前

soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);

final int sourceId = soundPool.load(getContext(), R.raw.swipe, 0);

SoundPool.OnLoadCompleteListener listener = new SoundPool.OnLoadCompleteListener() {

@Override

public void onLoadComplete(SoundPool soundPool, int i, int i1) {

soundPool.play(sourceId, 1, 1, 0, 0, 2);

}};

soundPool.setOnLoadCompleteListener(listener);

}

API21后使用其Builder

SoundPool.Builder  builder=newSoundPool.Builder();

builder.setMaxStreams(10);

builder.setAudioAttributes(null);//转换音频格式

SoundPoolsp=builder.build();//创建SoundPool对象

3、粘贴复制板ClipBoard

        Android提供的剪贴板框架,复制和粘贴不同类型的数据。数据可以是文本,图像,二进制流数据或其它复杂的数据类型。Android提供ClipboardManager、ClipData.Item和ClipData库使用复制和粘贴的框架。为了使用剪贴板的框架,需要把数据转化为剪辑对象,然后把该对象为全系统剪贴板。为了使用剪贴板,需要通过调用getSystemService()方法来实例化ClipboardManager的对象。

API23之前导包

importandroid.text.ClipboardManager;

源代码

package android.text;

/**

* @deprecated Old text-only interface to the clipboard.  See

* {@link android.content.ClipboardManager} for the modern API.

*/

@Deprecated

public abstract class ClipboardManager {

/**

* Returns the text on the clipboard.  It will eventually be possible

* to store types other than text too, in which case this will return

* null if the type cannot be coerced to text.

*/

public abstract CharSequence getText();

/**

* Sets the contents of the clipboard to the specified text.

*/

public abstract void setText(CharSequence text);

/**

* Returns true if the clipboard contains text; false otherwise.

*/

public abstract boolean hasText();

}

API23之后导包

importandroid.content.ClipData;

importandroid.content.ClipboardManager;

复制功能的代码

privateClipboardManagermyClipboard;

myClipboard= (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

ClipData myClip;

String text =website.getText().toString().trim();

myClip = ClipData.newPlainText("text",text);

myClipboard.setPrimaryClip(myClip);

粘贴功能的代码

ClipDataabc=myClipboard.getPrimaryClip();

ClipData.Itemitem=abc.getItemAt(0);

Stringtext=item.getText().toString();

你可能感兴趣的:(系统组件主要类应用)