zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    11 Jun 18 复习,HTTP
    11 Jun 18 Django
    8 Jun 18 复习,mysql
    8 Jun 18 Bootstrap
    7 Jun 18 复习,文件,函数,sorted,colletions
    7 Jun 18 Bootstrap
    pip 使用方法
    http协议 1.1
    mysql 的视图 触发器 事务 存储过程 内置函数 流程控制 索引
    day 29 守护进程/互斥锁/IPC通信机制/生产者消费者模型
  • 原文地址:https://www.cnblogs.com/yshyee/p/3805903.html
Copyright © 2011-2022 走看看