天天看点

Android Api Demos登顶之路(三十二)Alarm Service

这个demo演示了如何利用闹钟定时器启动一个服务,用法与上一个demo基本类似,只是启动的是服务而上个demo 发送是的广播。

* 这里需要注意的是:在本例中每隔20秒启动一次服务,而服务在启动后,向系统通知栏中发送了一个通知消息 而后单独开启一个线程去执行服务中需要进行的复杂操作,操作完成后结束服务。

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/info" />
    <Button 
        android:id="@+id/start_service_schedule"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Alarm Service"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"/>
    <Button 
        android:id="@+id/stop_service_schedule"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Alarm Service"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"/>

</LinearLayout>
           

MainActivity.java

public class MainActivity extends Activity {
    private PendingIntent senderService;
    private AlarmManager am;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(MainActivity.this, AlarmService.class);
        senderService = PendingIntent.getService(MainActivity.this, , intent,
                );

        setContentView(R.layout.activity_main);
        am = (AlarmManager) getSystemService(ALARM_SERVICE);

        Button bt_start = (Button) findViewById(R.id.start_service_schedule);
        Button bt_stop = (Button) findViewById(R.id.stop_service_schedule);
        bt_start.setOnClickListener(startServiceListener);
        bt_stop.setOnClickListener(stopServiceListener);
    }

    private OnClickListener startServiceListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            long firstTime = SystemClock.elapsedRealtime();
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
                     * , senderService);
            Toast.makeText(MainActivity.this, "定时启动服务任务已经开启!", ).show();
        }
    };

    private OnClickListener stopServiceListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            am.cancel(senderService);
            Toast.makeText(MainActivity.this, "定时启动服务任务已经停止!", ).show();
        }
    };

}
           

AlarmService.java

public class AlarmService extends Service {
    private static final int NOTIFICATION_ID = ;
    private NotificationManager nm;

    @Override
    public void onCreate() {
        super.onCreate();
        // 获取系统通知管理器
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 向系统通知栏发送通知消息,并在通知栏中显示消息
        showNotification();
        // AlarmService表示为线程的名称
        Thread thr = new Thread(null, mTask, "AlarmService");
        thr.start();
    }

    private Runnable mTask=new Runnable() {
        @Override
        public void run() {
            long endTime=System.currentTimeMillis()+*;
            while(System.currentTimeMillis()<endTime){
                //加一把同步锁
                synchronized (mBinder) {
                    try {
                        mBinder.wait(endTime-System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            //结束服务
            AlarmService.this.stopSelf();
        }
    };
    //定义一个IBinder接口的实例
    private IBinder mBinder=new Binder(){
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply,
                int flags) throws RemoteException {
            // TODO Auto-generated method stub
            return super.onTransact(code, data, reply, flags);
        }
    };

    @SuppressWarnings("deprecation")
    private void showNotification() {
        String text = "服务正在运行...";
        String label = "闹钟定时服务示例!";
        // 定义一个延迟意图,当我们点击这条通知消息时,再次启动我们的主程序
        PendingIntent contentIntent = PendingIntent.getActivity(this, ,
                new Intent(this, MainActivity.class), );
        // 定义一个notification
        Notification.Builder builder = new Builder(this);
        builder.setSmallIcon(R.drawable.stat_sample);
        builder.setContentText(text);
        builder.setWhen(System.currentTimeMillis());
        builder.setContentTitle(label);
        builder.setContentIntent(contentIntent);
        builder.setTicker(text);
        Notification notification = builder.build();
        //Notification notification=new Notification(R.drawable.stat_sample, text, System.currentTimeMillis());

        // 设置在系统通知栏中显示的通知消息的界面信息
         //notification.setLatestEventInfo(this, label, text, contentIntent);
        //发送消息通知
        nm.notify(NOTIFICATION_ID, notification);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //根据notification的Id取消对应的系统通知
        nm.cancel(NOTIFICATION_ID);
        Toast.makeText(this, "服务结束!", ).show();
    }

}
           

最后别忘了在配置文件中对服务进行配置

继续阅读