因爲並沒有公開的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後會自動收起通知欄,天天分享小知識,你學會了嗎?