Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Android实现电蚊香/Service服务管理类

$
0
0

实现这个实例需要的就是Service这个类的管理,我们用到的是启动Service,并在退出应用程序的时候关闭(Stop)Service,下面我们首先看下这个程序的运行截图:


图中显示的控件一个是ImageView,另一个是ImageButton,我们点击ImageButton之后可以控制程序的运行和关闭,这里我们看到的是关闭的状态。

当我们点击ImageButton之后,程序开始运行,并且在通知栏有相应的显示。

下面给出实现的截图:



下面给出实现的代码:

1.Service类

package irdc.ex10_08;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.IBinder;

/* 自定义MyService继承Service */
public class MyService extends Service
{
  private String MY_PREFS = "MosPre";
  private NotificationManager notiManager;
  private int mosStatus;
  private int notiId=99;
  private MediaPlayer myPlayer;
    
  @Override
  public void onCreate()
  {
    try
    {
      /* 取得NotificationManager */
      notiManager=
        (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
      /* Create MediaPlayer */
      myPlayer=new MediaPlayer();
      myPlayer = MediaPlayer.create(MyService.this, R.raw.killmosall);
      
      /* 读取防蚊服务状态(1:启动,0:关闭) */
      SharedPreferences pres = 
        getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
      if(pres !=null)
      {
        mosStatus = pres.getInt("status", 0);
      }  
      
      if(mosStatus==1)
      {
        /* 加一个Notification */
        setNoti(R.drawable.antimos,notiId,"防蚊服务启动");     
        /* 播放防蚊铃声 */
        if(!myPlayer.isPlaying())
        {
          myPlayer.seekTo(0);
          myPlayer.setLooping(true);
          myPlayer.start();
        }
      }
      else if(mosStatus==0)
      {
        /* 删除Notification */
        deleteNoti(notiId);
        /* 关闭防蚊铃声 */
        if(myPlayer.isPlaying())
        {
          myPlayer.setLooping(false);
          myPlayer.pause();
        }
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    super.onCreate();
  }
  
  @Override
  public void onDestroy()
  {
    try
    {
      /* Service关闭时释放MediaPlayer,
       * 并删除Notification */
      myPlayer.release();
      deleteNoti(notiId);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    super.onDestroy();
  }

  
  /* 新增Notification的method */
  public void setNoti(int iconImg,int iconId,String icontext)
  {
    /* 建立点选Notification留言条时,会执行的Activity */
    Intent notifyIntent=new Intent(this,EX10_08.class);  
    notifyIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
    /* 建立PendingIntent当为设定递延执行的Activity */ 
    PendingIntent appIntent=PendingIntent.getActivity(this,0,notifyIntent,0); 
    /* 建立Notification,并设定相关参数 */ 
    Notification myNoti=new Notification();
    /* 设定status bar显示的icon */
    myNoti.icon=iconImg;
    /* 设定notification发生时她时发叨预设声音 */
    myNoti.defaults=Notification.DEFAULT_SOUND;
    myNoti.setLatestEventInfo(this,"防蚊服务启动",icontext,appIntent);
    /* 送出Notification */
    notiManager.notify(iconId,myNoti);
  } 
  
  /* 删除Notification的method */
  public void deleteNoti(int iconId)
  {
    notiManager.cancel(iconId);
  }
  
  @Override
  public IBinder onBind(Intent arg0)
  {
    return null;
  }
}

2.主程序类

package irdc.ex10_08;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class EX10_08 extends Activity
{
  public static final String MY_PREFS = "MosPre";
  private ImageButton button01;
  private ImageView image01;
  private int mosStatus;
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    /* 加载main.xml Layout */
    setContentView(R.layout.main);
    
    /* 取得保存在SharedPreferences的防蚊状态 */
    SharedPreferences pres = 
      getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
    if(pres !=null)
    {
      mosStatus = pres.getInt("status", 0);
    }
    
    image01 = (ImageView)findViewById(R.id.image01);
    button01 = (ImageButton)findViewById(R.id.button01);
    
    /*检查mosStatus是否启动状态(1) */
    if (mosStatus==1)
    {
      /* 设置启动图案 */
      image01.setImageResource(R.drawable.mos_open);
      button01.setBackgroundResource(R.drawable.power_on);
    }
    else
    {
      /* 设置关闭图案 */
      image01.setImageResource(R.drawable.mos_close);
      button01.setBackgroundResource(R.drawable.power_off);
    }
    
    button01.setOnClickListener(new Button.OnClickListener()
    {
      @Override
      public void onClick(View v)
      {
        if (mosStatus==1)
        {
          SharedPreferences pres = 
            getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
          if(pres!=null)
          {
            /* 设定状态为关闭(0) */
            mosStatus=0;
            SharedPreferences.Editor ed = pres.edit(); 
            ed.putInt("status",mosStatus); 
            ed.commit();
          }
          /* 设定关闭图案 */
          image01.setImageResource(R.drawable.mos_close);
          button01.setBackgroundResource(R.drawable.power_off);
          /* 终止service */
          stopMyService(1);
        }
        else if(mosStatus==0)
        {
          SharedPreferences pres = 
            getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
          if(pres!=null)
          {
            /* 设定状态为启动(1) */
            mosStatus=1;
            SharedPreferences.Editor ed = pres.edit(); 
            ed.putInt("status",mosStatus); 
            ed.commit();
          }
          /*设定启动图案*/
          image01.setImageResource(R.drawable.mos_open);
          button01.setBackgroundResource(R.drawable.power_on);
          /* 启动service */
          startMyService();
        }
        else
        {
          Toast.makeText(EX10_08.this,"系统错误",Toast.LENGTH_LONG)
            .show();
        }  
      }
    });
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {    
    /* 叵丈离开的menu */
    menu.add(0,1,1,"").setIcon(R.drawable.menu_exit); 
    return super.onCreateOptionsMenu(menu);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    switch(item.getItemId())
    {
      case (1):
        /* 离开前ALERT提醒 */
        new AlertDialog.Builder(EX10_08.this)
        .setTitle("Message")
        .setMessage("确定要离开吗?")
        .setPositiveButton("确定",
          new DialogInterface.OnClickListener()
          {
            public void onClick(DialogInterface dialoginterface,int i)
            {           
              finish();
            }
          }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
          public void onClick(DialogInterface dialoginterface, int i)   
          {
          }
        }).show();
        break;
    }
    return super.onOptionsItemSelected(item);
  }
  
  public void startMyService()
  {
    try
    {
      /* 先终止之前可能还在运行的service */
      stopMyService(0);
      /* 启动MyService */
      Intent intent = new Intent( EX10_08.this, MyService.class); 
      intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); 
      startService(intent);
      Toast.makeText(EX10_08.this,getResources().getString(R.string.start),
                     Toast.LENGTH_LONG).show();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }
  
  public void stopMyService(int flag)
  {
    try
    {
      /* 停止MyService */
      Intent intent = new Intent( EX10_08.this, MyService.class );
      stopService(intent);
      if(flag==1)
      {
        Toast.makeText(EX10_08.this,getResources().getString(R.string.stop),
                       Toast.LENGTH_LONG).show();
      }
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }
}

3.Service的注册

 <service
      android:name=".MyService"
      android:exported="true" 
      android:process=":remote"
    />

4.布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:background="@drawable/white"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center_horizontal"
>
  <ImageView
    android:id="@+id/image01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="30dip"
  />
  <ImageButton
    android:id="@+id/button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
  />
</LinearLayout>


作者:DLUTBruceZhang 发表于2013-2-9 15:55:01 原文链接
阅读:95 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>