Android入门总结-Service

2017-03-11  本文已影响36人  克罗地亚催眠曲

最近看了一下Android,只看书不总结一下,总感觉东西并没有放在脑子里,人过留名,雁过留声,遂写下这篇总结。

书本看的是《Android编程兵书》,但这篇总结的大纲是按照《第一行代码》的章节目录撰写的。两本书的内容结构大致相同,Android入门的话只看其中一本就够了。

Service:适合执行那些不需要和用户交互而且还要求长期运行的任务,不依赖于任何界面,依赖于创建服务所在的应用程序。
java创建线程的两种方法

//  方法一
class MyThread extends Thread{
    public void run(){

    }
}

new MyThread().start();

//方法二
class Mythread implements Runnable{
    public void run(){

    }
}
MyThread myThread = new MyThrea();
new Thread(myThread).start();   // Thread构造函数接收一个Runnable参数

//方法三 匿名类
new Thread(new Runnable(){
    public void run(){

    }
}).start();

Android 不允许在子线程中操作UI
解决方法:
Android异步处理机制示例代码

public class MainActivity extends Activity implements OnClickListener{
    
    public static final int UPDATE_TEXT = 1;
    private TextView text;
    private Button changeText;

    private Handler handler = new Handler(){

        public void handleMessage(Message msg){
            switch(msg.what){
            case UPDATE_ETXT:
                text.setText("Nice to meet you");
                break;
            default:
                break;
            }
        }
    }

    public void onClick(View v){
        switch(v.getId()){
        case R.id.change_text:
            new Thread(new Runnable(){
                public void run(){
                    Message message = new Message();
                    message.what = UPDATE_ETXT;
                    handler.sendMessage(message);
                }
            }).start();
            break;
        default:
            break;
        }
    }

}

使用AsyncTask 示例代码

class DownloadTask extends AsyncTask<Void, Integer, Boolean>{

    protected void onPreExecute(){
        progressDialog.show();
    }

    protected Boolean doInBackground(Void... params){
        try{
            while(true){
                int downloadPercent = doDownload();
                publishProgress(downloadPercent);
                if(downloadPercent >= 100){
                    break;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return true;
    }

    protected void onProgressUpdate(Integer... values){
        progressDialog.setMessage("Downloaded " + values[0] + "%");
    }

    protected void onPostExecute(Boolean result){
        progressDialog.dismiss();   // 关闭进度对话框
        if(result){
            Toast.makeText(context, "Download successed ", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(context, "Download failed", Toast.LENGTH_SHORT).show();
        }
    }
}

使用服务

onCreate()方法在服务第一次创建的时候调用,onStartCommand()方法则在每次启动服务的时候都会调用,只要在Service中的任何一个地方调用stopSelf()方法就能停止服务。还可用stopService()停止服务

activity绑定服务

public class MyService extends Service{
    
    private DownloadBinder mBinder = new DownloadBinder();

    class DownloadBinder extends Binder{
        public void startDownload(){
            Log.d("MyService", "startDownload executed");
        }

        public int getProgress(){
            Log.d("MyService", "getProgress executed");
            return 0;
        }
    }
    
    public Ibinder onBind(Intent intent){
        return mBinder;
    }
    
    public void onCreate(){
        super.onCreate();
    }
    
    public onStartCommand(Intent intent, int flags, int startId){
        return super.onStartCommand(intent, flags, startId);
    }

    public void onDestroy(){
        super.onDestroy();
    }
}

Myservice.DownloadBinder downloadBinder;

ServiceConnection connection - new ServiceConnection(){
    
    public void onServiceDisconnected(ComponentName name){}

    public void onServiceConnected(ComponentName name, Ibinder service){
        downloadBinder = (Myservice.DownloadBinder) service;
        downloadBinder.startDownload();
        downloadBinder.getProgress();
    }
}

Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);// BIND_AUTO_CREATE参数表示绑定后自动创建服务,onCreate执行,onStartCommand不执行

//启动服务
Intent startIntent = new Intent(this, Myservice.class);
startService(startIntent);

//停止服务
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);

前台服务:防止内存不足是系统收回后台服务。前台服务在状态栏有显示。
示例代码

//  MyService 中
Notification notification = new Notification(R.drawable.ic_launcher, "Notification comes", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "this is title", "this is content", pendingIntent);
startForeground(1, notification);

使用IntentService:服务运行在子线程中且运行结束后自动停止,其余和普通Service相似

Android后台执行定时任务:方法有两种Java API的Timer类和Android的Alarm机制。Timer不适用于需要长期在后台执行的任务。Android会在长时间无操作的情况下让CPU进入睡眠状态,这可能导致Timer中的定时任务无法正常执行。Alarm机制则不存在此问题,因为Alarm具有唤醒CPU的功能
Android Alarm 示例代码

public void LongRunningService extends Service{
    
    pubic Ibinder onBind(Intent intent){
        return null;
    }

    public int onStartCommand(Intent intent, int flags, int startId){
        new Thread(new Runnable(){
            public void run(){
                Log.d("LongRunningService", "executed at " + new Date().toString());
            }
        }).start();

        AlarmManager manager = getSystemService(ALARM_SERVICE);
        int anHour = 60 * 60 * 1000; // 一个小时的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;

        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

        return super.onStartCommand(intent, flags, startId);
    }
}

//在onReceive方法中再次启动LongRunningService,形成一个永久的循环
public class AlarmReceiver extends BroadcastReceiver{
    
    pubic void onReceive(Context context, Intent intent){
        Intent i = new Intent(context, LongRunningService.class);
        context.startService(i);
    }
}

Tips
1、iOS不支持后台,当应用程序不在前台运行时就会进入到挂起状态。
而Android沿用了Symbian的习惯加入了后台功能,使得应用程序即使在关闭的情况下仍然可以在后台继续运行。
2、若既调用了startService又调用了BindService,需要同时调用stopService和unbindService方法,onDestroy方法才会执行
3、什么是ANR?
Application Not Responding

上一篇下一篇

猜你喜欢

热点阅读