因为并没有公开的API提供这个功能,所以只能通过反射来调用了,简单demo如下:
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.lang.reflect.Method;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button = findViewById(R.id.open_statusbar);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//判断系统版本号
String methodName = (Build.VERSION.SDK_INT <= 16) ? "expand" : "expandNotificationsPanel";
doInStatusBar(getApplicationContext(), methodName);
}
});
}
@Override
protected void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//判断系统版本号
String methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels";
doInStatusBar(getApplicationContext(), methodName);
}
}, 10000);
}
private static void doInStatusBar(Context mContext, String methodName) {
try {
Object service = mContext.getSystemService("statusbar");
Method expand = service.getClass().getMethod(methodName);
expand.invoke(service);
} catch (Exception e) {
e.printStackTrace();
}
}
}
一个简单的按钮添加点击事件,点击后下拉通知栏,从页面加载开始10s后会自动收起通知栏,天天分享小知识,你学会了吗?