Android IntentService 与Alarm开启任务关闭任务

1:MyService

public class MyService  extends IntentService{
    AlarmManager alarmManager = null;
    PendingIntent alarmIntent = null;

    public MyService(){
        super("MyService");
    }

    public MyService(String name){
        super(name);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        alarmManager = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
        Intent intentTo = new Intent("com.yan.receive.MY_ALARM");
        alarmIntent = PendingIntent.getBroadcast(this, 0, intentTo, 0);
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        //final Context context = this.getApplicationContext();

        int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
        long triggerAtMillis = SystemClock.elapsedRealtime()+(5*1000);//执行间隔时间5s
        long intervalMillis = 2*1000;
        alarmManager.setInexactRepeating(alarmType, triggerAtMillis, intervalMillis, alarmIntent);

        System.out.println("============执行============");
    }
}

2:MyAlarmReceiver

public class MyAlarmReceiver  extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Intent startIntent = new Intent(context, MyService.class);
        context.startService(startIntent);
    }

}

3:MainActivity

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        Button btnStart;
        Button btnClose;
        AlarmManager alarmManager = null;
        PendingIntent alarmIntent = null;

        public PlaceholderFragment() {
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,false);

            btnStart = (Button)rootView.findViewById(R.id.btnStart);
            btnClose = (Button)rootView.findViewById(R.id.btnClose);

            btnStart.setOnClickListener(btnClickLIstener());
            btnClose.setOnClickListener(btnClickLIstener());

            return rootView;
        }

        OnClickListener btnClickLIstener(){
            return new OnClickListener(){
                @Override
                public void onClick(View arg0) {
                    switch(arg0.getId()){
                    case R.id.btnStart:
                        // 启动服务
                        Intent myIntent = new Intent(getActivity(),  MyService.class);
                        getActivity().startService(myIntent);
                        System.out.println("=========启动服务");
                        break;
                    case R.id.btnClose:
                        alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
                        Intent intentTo = new Intent("com.yan.receive.MY_ALARM");
                        alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intentTo, 0);
                        if(null != alarmIntent){
                            alarmManager.cancel(alarmIntent);
                        }
                        System.out.println("=========停止Alarm");
                        getActivity().stopService(new Intent(getActivity(),  MyService.class));
                        System.out.println("=========停止服务");
                        break;
                    }
                }
            };
        }
    }
}

4:activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.intentservice.MainActivity"
    tools:ignore="MergeRootFrame" />

5:fragment_main.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.intentservice.MainActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/btnStart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启任务" />

    <Button
        android:layout_below="@id/btnStart"
        android:id="@+id/btnClose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭任务" />
</RelativeLayout>

6:AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.intentservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <receiver
            android:name="com.yan.receive.MyAlarmReceiver"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.yan.receive.MY_ALARM" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.yan.service.MyService"
            android:enabled="true"
            android:exported="false" />

        <activity
            android:name="com.example.intentservice.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Android IntentService 与Alarm开启任务关闭任务

时间: 2024-10-22 02:12:09

Android IntentService 与Alarm开启任务关闭任务的相关文章

实现开启和关闭android移动网络(转)

开启和关闭移动数据网络有两种方法:一种是通过操作系统的数据库改变APN(网络接入点),从而实现开启和关闭移动数据网络,另一种是通过反射调用系统(ConnectivityManager)的setMoblieDataEnabled方法,通过操作该方法开启和关闭系统移动数据,同时也可以通过反射调用getMoblieDataEnabled方法获取当前的开启和关闭状态. 第一种方式: 通过APN的方式开启和关闭很威猛啊,为什么这么说呢,废话不多说,先看代码: 1. 匹配类: [java] view pla

Android网络开启、关闭整理

近段时间由于要对手机网络状况进行判断.开启和关闭,从网上找了些资料,现整理如下 包含了对WiFi.GPRS.飞行模式的开启.关闭以及一些状态的检测,在小米和三星平板上测试均通过 [java] view plaincopy package com.my.device_admin.business; import java.lang.reflect.Method; import android.content.Context; import android.content.Intent; impor

Android 如何开启与关闭adb 的认证机制(google adb secure) (adb RSA 指纹认证)

前言 欢迎大家我分享和推荐好用的代码段~~ 声明          欢迎转载,但请保留文章原始出处: CSDN:http://www.csdn.net 雨季o莫忧离:http://blog.csdn.net/luckkof 正文 [Description] 如何开启与关闭adb 的认证机制(google adb secure) [Keyword] adb secure , ro.adb.secure , adb RSA 指纹认证 [Solution] MTK 版本默认关闭adb 的地址认证机制,

[Android Traffic] Android网络开启、关闭整理

转载: http://blog.csdn.net/tu_bingbing/article/details/8469871 近段时间由于要对手机网络状况进行判断.开启和关闭,从网上找了些资料,现整理如下 包含了对WiFi.GPRS.飞行模式的开启.关闭以及一些状态的检测,在小米和三星平板上测试均通过 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/> <uses-permis

Android 蓝牙设备的开启与关闭功能的实现

本文主要是关于Android蓝牙设备的开启与关闭,很简单,详细请看代码. 1.MainActivity.java public class MainActivity extends Activity { private String TAG="MainActivity"; private Button startBtn; private Button stopBtn; BluetoothAdapter mBluetoothAdapter; @Override protected voi

Android的WiFi开启与关闭

注意:要首先注册开启和关闭WiFi的权限, <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wyl.wifi" android:versionCode="1" android:versionName

Android开发中数据连接的开启和关闭

最近在做Android开发的过程中,我想要通过代码来实现数据连接的开启和关闭,最初我将目标锁定为ConnectivityManager类,但是在翻阅了Android官方API后并没有找到相关的方法,如图1. 图1 但是据说Android的一些类的某些方法的API是非公开的,所以我又做了如下尝试,获得ConnectivityManager在加载时的Class对象,并查看了其中的方法,代码如下: 1 ConnectivityManager connectivityManager = null; 2

Android IntentService vs Service

Android IntentService vs Service 众所周知,Android中的Service是用于后台服务的,当应用程序被挂到后台的时候,为了保证应用中某些功能仍然可以工作而引入了Service,比如播放音乐.针对service,官方文档有2点重要说明: 1. A Service is not a separate process. The Service object itself does not imply it is running in its own process;

Android IntentService使用全面介绍及源码解析

一 IntentService介绍 IntentService定义的三个基本点:是什么?怎么用?如何work? 官方解释如下: //IntentService定义的三个基本点:是什么?怎么用?如何work?*/ 1.IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. 2.Clients send requests through