這次要來教的是如何製作一個懸浮視窗的提醒,這個功能在許多目前市面上常用的APP上都能看到,例如:Line、FB等....都有這種提醒的功能,現在就來示範如何使用此功能。
先簡單設計出一個頁面,寫出一個Button作為觸發懸浮視窗的元件就好。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕"/>
</RelativeLayout>
設計好XML之後,就能開始製作懸浮視窗的功能了。
先做好按鈕的監聽器,接著在觸發功能輸入觸發懸浮視窗的事件,下面先解析一些程式碼的片段。Manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
此為手機通知的總管理
isOpened = Manager.areNotificationsEnabled();
if(!isOpened){
Toast.makeText(MainActivity.this,"請開啟通知權限", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, MainActivity.this.getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, MainActivity.this.getApplicationInfo().uid);
MainActivity.this.startActivity(intent);
}
這段用來判斷是否有開啟通知,如沒有則導入到系統中NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
設定NotificationChannel的ID和NAME,第三個參數是用以表示通知的重要性
下面附上完整程式碼
public class MainActivity extends AppCompatActivity {
Button button;
boolean isOpened;
String channelId = "channel1";
String channelName = "name";
NotificationManager Manager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isOpened = Manager.areNotificationsEnabled();
if(!isOpened){
Toast.makeText(MainActivity.this,"請開啟通知權限", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, MainActivity.this.getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, MainActivity.this.getApplicationInfo().uid);
MainActivity.this.startActivity(intent);
}
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
Manager.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(MainActivity.this,channelId);
builder.setSmallIcon(R.drawable.aa)
.setChannelId(channelId)
.setContentTitle("標題")
.setContentText("內容").build();
Manager.createNotificationChannel(channel);
Manager.notify(1, builder.build());
}
});
}
}
最後在AndroidManifest中加入權限<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
加入完後才能進到設定頁面。