1)设置StandupReciver.java
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class StandupReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"inside Recevier",Toast.LENGTH_SHORT).show();
NotificationManager myManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mynoti=new NotificationCompat.Builder(context);
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 2.0f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
mynoti.setContentTitle("Stand up Notification");
mynoti.setContentText("you need to stand up");
mynoti.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
mynoti.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
mynoti.setSmallIcon(android.R.drawable.ic_btn_speak_now);
Intent il=new Intent(context,MainActivity.class);
PendingIntent pd= PendingIntent.getActivity(context,0,il,0);
mynoti.setContentIntent(pd);
mynoti.setAutoCancel(true);
myManager.notify(1,mynoti.build());
}}
2) AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<receiver
android:name=".StandupReciver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.xyz.myown.recevier.Message"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
3)MainActivity.java
开始方法
Toast.makeText(getApplicationContext(), "Start", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setAction("com.xyz.myown.recevier.Message");
i.addCategory("android.intent.category.DEFAULT");
PendingIntent pd = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 10, pd);
停止方法
Toast.makeText(getApplicationContext(),"Stop",Toast.LENGTH_SHORT).show();
Intent i=new Intent();
i.setAction("com.xyz.myown.recevier.Message");
i.addCategory("android.intent.category.DEFAULT");
PendingIntent pd= PendingIntent.getBroadcast(getApplicationContext(),0,i,0);
alarmManager.cancel(pd);