以下紀錄使用Eclipse開發手機APP警報的心得如下
1. 專案開啟後,AndroidManifest.xml中必須在</manifest>之前插入
<uses-permission android:name="android.permission.VIBRATE" />
讓程式註冊震動的服務
2. 在layout的activity_main.xml(預設)檔名中加入一個按鈕 [notifyButn]
3. MainActivity.java的程式碼
package com.example.alarmtest;
import android.app.Activity;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button buttonCreateNotification;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreateNotification = (Button)findViewById(R.id.notifyButn);
buttonCreateNotification.setOnClickListener(
new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
createNotification(getBaseContext());
}}
);
}
private void createNotification(Context context){
NotificationManager notificationManager
= (NotificationManager)context.getSystemService(
Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent
= PendingIntent.getActivity(context, 0, intent, 0);
long[] vibratepattern = {100, 400, 500, 400};
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("標題")
.setContentText("文字")
.setContentInfo("信息")
.setTicker("票")
.setLights(0xFFFFFFFF, 1000, 1000)
.setVibrate(vibratepattern)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.build();
notificationManager.notify(R.drawable.ic_launcher, notification);
}
}
參考來源: 這邊
沒有留言:
張貼留言