Android利用反射下拉出通知欄

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章