Android随记
学习笔记
- 安卓
- 1、recycleview
- 2、Eventbus使用机制
- 3、检查是否有网络
- 4、OKHttp详解
- 5、音视频焦点切换详解
安卓
1、recycleview
((TextView) layoutManager.findViewByPosition(mCurSiteIndex).findViewById(R.id.tv_stationname)).setTextColor(Color.parseColor("#52A8FF"));
找到recycleview中的父布局,要强制转换类型才能设置具体字体颜色
2、如果在fragment中出现无法用tv_sitefirst.setText(stations.get(0).getName());
赋值
stations = mCurLine.getStations();
用 = 赋值,很有可能会造空指针异常,此时可以将上面代码改为
stations.clear(); stations.addAll(mCurLine.getStations());
2、Eventbus使用机制
- 先在xml里面定义解析出想要的value值,然后通过下面的代码发送通知
EventBus.getDefault().post(new StationnameEvent(value));
- 然后定义一个StationnameEvent类
public class StationnameEvent {
private String txt;
public StationnameEvent(@NonNull String txt) {
this.txt = txt;
}
public String getTxt() {
return txt;
}
}
- 在要获取的地方,进行注册获取
@Subscribe(threadMode = ThreadMode.MAIN)
public void onReceiveStationnameEvent(StationnameEvent event) {
//TODO 里面执行具体要执行的东西,比如显示view视图啥的.
}
特别注意,onReceiveStationnameEvent,这个名称一定要和类的名称一模一样,否则接收不到消息。
3、检查是否有网络
public boolean isNetworkAvailable(Activity activity)
{
Context context = activity.getApplicationContext();
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null)
{
return false;
}
else
{
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0)
{
for (int i = 0; i < networkInfo.length; i++)
{
System.out.println(i + "===状态===" + networkInfo[i].getState());
System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
4、OKHttp详解
https://www.jianshu.com/p/9aa969dd1b4d
在AndroidManifest.xml中加入联网权限
<uses-permission android:name="android.permission.INTERNET" />
1、拿到OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient()
2、构造Request对象
Request request = new Request.Builder()
.get()
.url("https:www.baidu.com")
.build();
这里我们采用建造者模式和链式调用指明是进行Get请求,并传入Get请求的地址
如果我们需要在get请求时传递参数,我们可以以下面的方式将参数拼接在url之后
https:www.baidu.com?username=admin&password=admin
3、将Request封装为Call
Call call = client.newCall(request);
4、根据需要调用同步或者异步请求方法
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();
//异步调用,并设置回调函数
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "get failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
contentTv.setText(res);
}
});
}
});
- 同步调用会阻塞主线程,一般不适用
- 异步调用的回调函数是在子线程,我们不能在子线程更新UI,需要借助于runOnUiThread()方法或者Handler来处理
注意:::对okHttp连接超时进行处理
public void onFailure(Call call, IOException e) {
Log.e(TAG, mPlayInfo.getPdfilename() + "下载进度:连接失败-" + e.getMessage());
// 失败终端线程
if(e instanceof SocketTimeoutException && serversLoadTimes<BaseConstant.maxLoadTimes){如果超时并未超过指定次数,则重新连接
Log.e(TAG, mPlayInfo.getPdfilename() + "下载进度:超时" + e.getMessage()+"尝试第 "+serversLoadTimes+" 次");
serversLoadTimes++;
okHttpClient.newCall(call.request()).enqueue(this);
}else {
Log.e(TAG, mPlayInfo.getPdfilename() + "下载出错" + e.toString());
interrupt();
}
}
5、音视频焦点切换详解
1、在播放视频的类中,进行注册
private AudioManager mAudioManager;
private AudioFocusRequest audioFocusRequest;
private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener;
2、在oncreate进行初始化
// 处理音频焦点-处理多个程序会来竞争音频输出设备
mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
Log.e("Playfragment ", "音频焦点切换:" + focusChange);
/* if (videoView.getBackground()==null){
Log.e("视频不在播放", "音频焦点切换:" + focusChange);
return;
}*/
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
// 获取audio focus
Log.e("Playfragment ", "获得音频焦点,提高音量" );
setVolume(1, videoView);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// 失去audio focus很长一段时间,必须停止所有的audio播放,清理资源
Log.e("Playfragment ", "onAudioFocusChange长时间失去音频焦点,降低音量,释放资源");
setVolume(0, videoView);
break;
/*case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// 暂时失去audio focus,但是很快就会重新获得,在此状态应该暂停所有音频播放,但是不能清除资源
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
break;*/
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.e("Playfragment ", "onAudioFocusChange短暂失去音频焦点,降低音量");
// 暂时失去 audio focus,但是允许持续播放音频(以很小的声音),不需要完全停止播放。
setVolume(0, videoView);
break;
default:
break;
}
}
};
3、调节音量策略
/**
* @param volume 音量大小
* @param object VideoView实例
* ///VideoView 反射 MediaPlayer控制音量 http://blog.csdn.net/u012874222/article/details/73303264
* 静音有效果,恢复无效
*/
private void setVolume(float volume, Object object) {
try {
Log.e("Playfragment ", "播放节目,音频焦点切换设置音量:" + volume);
Class<?> forName = Class.forName("android.widget.VideoView");
Field field = forName.getDeclaredField("mMediaPlayer");
field.setAccessible(true);
MediaPlayer mMediaPlayer = (MediaPlayer) field.get(object);
mMediaPlayer.setVolume(volume, volume);
} catch (Exception e) {
Log.e("Playfragment ", "播放节目,音频焦点切换设置音量" + volume + "出错:" + e.toString());
}
}
4、在onprepare中进行request请求
mAudioManager.requestAudioFocus(mAudioFocusChangeListener,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
5、进行释放资源,ondestroy
mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
二、在需要短暂播放声音的地方(如到站播报)
1、在oncreate中
// 处理音频焦点-处理多个程序会来竞争音频输出设备
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 对于Android 8.0+
audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setOnAudioFocusChangeListener(mAudioFocusChangeListener).build();
audioFocusRequest.acceptsDelayedFocusGain();
}
2、在具体播放声音的逻辑中
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mAudioManager.requestAudioFocus(audioFocusRequest);
Log.e(TAG, "到站播报请求音频焦点");
} else {
// 小于Android 8.0
int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// could not get audio focus.
Log.e(TAG, "到站播报请求音频焦点出错:"+result);
}else {
Log.d(TAG, "到站播报请求音频焦点<8,"+result);
}
}
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mAudioManager.abandonAudioFocusRequest(audioFocusRequest);
Log.e(TAG, "到站播报释放音频焦点");
}else {
mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
Log.e(TAG, "到站播报释放音频焦点<8");
}
mIsPlaying = false;
mHandler.removeCallbacks(this);
}
}, 3000);
break;
4、包名就是 com.####.
应用签名下载应用签名软件下载