【黑馬Android】(08)activity生命週期/橫豎屏切換的生命週期/任務棧的概念/廣播接收者ip撥號器/進程的優先級&爲什麼使用服務

activity生命週期


完整生命週期  oncreate--onstart--onresume--onpause--onstop--ondestory

 

可視生命週期  onstart--onresume--onpause--onstop

 

前臺生命週期  onresume--onpause  界面用戶仍然可見,但是失去焦點 

 

使用場景:

1.應用程序退出自動保存數據   ondestory   oncreate

2.應用程序最小化 暫停的操作  onstop onstart  視頻播放器

3.遊戲的暫停和開始 前臺生命週期

package com.itheima.lifecycle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
	//被創建的時候調用的方法 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		System.out.println("oncreate");
	}

	//被銷燬的時候調用的方法
	@Override
	protected void onDestroy() {
		System.out.println("ondestory");
		super.onDestroy();
	}
	//當activity界面用戶可見的時候調用的方法
	@Override
	protected void onStart() {
		System.out.println("onstart");
		super.onStart();
	}
	@Override
	protected void onRestart() {
		System.out.println("onrestart");
		super.onRestart();
	}	
	
	//當activity界面用戶不可見的時候調用的方法
	@Override
	protected void onStop() {
		System.out.println("onstop");
		super.onStop();
	}
	
	//界面開始獲取到焦點對應的方法。 (界面按鈕可以被點擊,文本框可以輸入內容)
	@Override
	protected void onResume() {
		System.out.println("onresume");
		super.onResume();
	}
	//界面失去焦點對應的方法(暫停)(按鈕不可被點擊,文本框不可輸入內容,但是界面用戶仍然能看見)
	@Override
	protected void onPause() {
		System.out.println("onpause");
		super.onPause();
	}
	
	public void click(View view){
		Intent intent = new Intent(this,SecondActivity.class);
		startActivity(intent);
	}	
}

橫豎屏切換的生命週期

<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"
    tools:context=".MainActivity" >

    <Button
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="重拳" />

    <TextView
        android:id="@+id/tv_blood"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="100" />

</RelativeLayout>

默認情況下橫豎屏切換activity會被銷燬然後重新創建。

package com.itheima.kof97;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 默認情況下橫豎屏切換activity會被銷燬然後重新創建。
 * @author Administrator
 *
 */
public class MainActivity extends Activity {
	private TextView tv_blood;
	private int blood = 100;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("oncreate");
		setContentView(R.layout.activity_main);
		tv_blood = (TextView) findViewById(R.id.tv_blood);
	}

	public void click(View view){
		blood --;
		tv_blood.setText("對方的生命值:"+blood);
		if(blood<0){
			Toast.makeText(this, "K.O.!", 1).show();
		}
	}
	
	//被銷燬的時候調用的方法
		@Override
		protected void onDestroy() {
			System.out.println("ondestory");
			super.onDestroy();
		}
		//當activity界面用戶可見的時候調用的方法
		@Override
		protected void onStart() {
			System.out.println("onstart");
			super.onStart();
		}
		@Override
		protected void onRestart() {
			System.out.println("onrestart");
			super.onRestart();
		}
		
		
		//當activity界面用戶不可見的時候調用的方法
		@Override
		protected void onStop() {
			System.out.println("onstop");
			super.onStop();
		}
		
		//界面開始獲取到焦點對應的方法。 (界面按鈕可以被點擊,文本框可以輸入內容)
		@Override
		protected void onResume() {
			System.out.println("onresume");
			super.onResume();
		}
		//界面失去焦點對應的方法(暫停)(按鈕不可被點擊,文本框不可輸入內容,但是界面用戶仍然能看見)
		@Override
		protected void onPause() {
			System.out.println("onpause");
			super.onPause();
		}	

}

android:configChanges="orientation|keyboardHidden|screenSize"

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:name="com.itheima.kof97.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>

任務棧的概念

1.一個應用程序一般都是由多個activity組成的。

2.任務棧(task stack)(別名back stack後退棧) 記錄存放用戶開啓的activity的。

3.一個應用程序一被開啓系統就給他分配一個任務棧,當所有的activity都退出的時候,任務棧就清空了。

4.任務棧的id是一個integer的數據類型 自增長的。

5.android操作系統裏面會存在多個任務棧,一個應用程序一個任務棧。

6.桌面應用和一般的應用程序是一樣的,任務棧的行爲也是一樣。

7.默認情況下, 關閉掉一個應用程序,清空了這個應用程序的任務棧。應用程序的進程還會保留。

 

 

爲什麼要引入任務棧的概念:

windows下 可以通過點擊任務欄 切換任務

android下 長按小房子 切換任務

 

爲了記錄用戶開啓了那些activity,記錄這些activity開啓的先後順序,google引入任務棧(task stack)概念,幫助維護好的用戶體驗。

activity的啓動模式

activity的啓動模式:

1. standard   默認標準的啓動模式, 每次startActivity都是創建一個新的activity的實例。

              適用於絕大大數情況

2. singleTop  單一頂部,如果要開啓的activity在任務棧的頂部已經存在,就不會創建新的實例,

              而是調用 onNewIntent() 方法。

              應用場景: 瀏覽器書籤。 避免棧頂的activity被重複的創建,解決用戶體驗問題。

3. singletask 單一任務棧 , activity只會在任務棧裏面存在一個實例。如果要激活的activity,在

              任務棧裏面已經存在,就不會創建新的activity,而是複用這個已經存在的activity

              調用 onNewIntent() 方法,並且清空當前activity任務棧上面所有的activity

              應用場景:瀏覽器activity, 整個任務棧只有一個實例,節約內存和cpu的目的

              注意: activity還是運行在當前應用程序的任務棧裏面的。不會創建新的任務棧。

 

4. singleInstance  單態 單例模式

              單一實例,整個手機操作系統裏面只有一個實例存在。不同的應用去打開這個activity

      共享 公用的同一個activity

              他會運行在自己單獨,獨立的任務棧裏面,並且任務棧裏面只有他一個實例存在。

              應用場景:呼叫來電界面 InCallScreen

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.taskstack.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>
        <activity android:name="com.itheima.taskstack.SecondActivity"
            android:launchMode="singleInstance"
            >
            <intent-filter>
                <action android:name="com.itheima.task.single"/>
                <category android:name="android.intent.category.DEFAULT" />

            </intent-filter>
        </activity>
    </application>

</manifest>
<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"
    tools:context=".MainActivity" >

    <TextView 
          android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="我是界面01"
        android:textSize="30sp"
        />
    
    
    <Button
        android:onClick="open01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="開啓界面01" />

    <Button
        android:onClick="open02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="開啓界面02" />

</LinearLayout>
<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"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="我是界面02"
        android:textSize="30sp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="open01"
        android:text="開啓界面01" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="open02"
        android:text="開啓界面02" />

</LinearLayout>
package com.itheima.taskstack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class SecondActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		System.out.println("02activity被創建了。任務棧id:"+getTaskId());
	}
	public void open01(View view){
		Intent intent = new Intent(this,MainActivity.class);
		startActivity(intent);
	}
	public void open02(View view){
		Intent intent = new Intent(this,SecondActivity.class);
		startActivity(intent);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		System.out.println("02activityonnew intnet。任務棧id:"+getTaskId());
		super.onNewIntent(intent);
	}
	
}
package com.itheima.taskstack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		System.out.println("01activity被創建了。任務棧id:"+getTaskId());
	}

	public void open01(View view){
		Intent intent = new Intent(this,MainActivity.class);
		startActivity(intent);
	}
	public void open02(View view){
		Intent intent = new Intent(this,SecondActivity.class);
		startActivity(intent);
	}
}

廣播接收者ip撥號器

四大組件:

Activity

Content provider 內容提供者

Broadcast receiver 廣播接受者

Service  服務

 

電臺:   發送廣播

收音機: 接受廣播

 

android系統下的廣播:

電池電量低。

電池充電完畢

短信到來了

程序安裝卸載

sd卡卸載 安裝

 

1.寫一個類繼承廣播接受者

2.在清單文件配置關心的動作

3.一旦廣播事件發生了,就會執行廣播接受者的onreceive方法

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.ipdail.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>
        <!-- 配置廣播接受者 -->
        <receiver android:name="com.itheima.ipdail.OutCallReceiver">
            <intent-filter>
                <!-- 配置廣播接收者關心的事件是外撥電話 -->
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
            </intent-filter>
        </receiver>
        
    </application>

</manifest>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請設置ip號碼" />
    <EditText 
        android:id="@+id/et_number"
         android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        />
	<Button 
	    android:onClick="save"
	     android:layout_width="fill_parent"
        android:layout_height="wrap_content"
	    android:text="保存"
	    />
</LinearLayout>
package com.itheima.ipdail;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

/**
 * 1.創建一個收音機 繼承廣播接受者
 *
 */
public class OutCallReceiver extends BroadcastReceiver {
	//當接收到消息對應的方法
	@Override
	public void onReceive(Context context, Intent intent) {
		String number = getResultData();
		System.out.println("哈哈,有電話打出去了"+number);
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		String ipnumber = sp.getString("ipnumber", "");
		//判斷是否是長途。是否有前綴
		setResultData(ipnumber+number);
	}
}
package com.itheima.ipdail;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText et_number;
	private SharedPreferences sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_number = (EditText) findViewById(R.id.et_number);
		sp = getSharedPreferences("config", MODE_PRIVATE);
	}

	public void save(View view){
		String ipnumber = et_number.getText().toString().trim();
		if(TextUtils.isEmpty(ipnumber)){
			Toast.makeText(this, "清除ip號碼成功", 0).show();
		}else{
			Toast.makeText(this, "設置ip號碼成功", 0).show();
		}
		Editor editor = sp.edit();
		editor.putString("ipnumber", ipnumber);
		editor.commit();
	}

}

sd卡的廣播事件

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.sdcardmointor.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>
        <receiver android:name="com.itheima.sdcardmointor.SDStatusReceiver">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
                <action android:name="android.intent.action.MEDIA_REMOVED"/>
               	<data android:scheme="file"></data>
            </intent-filter>
        </receiver>
    </application>

</manifest>
package com.itheima.sdcardmointor;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SDStatusReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "sd卡別移除,微信頭像或者圖片暫時不可用", 1).show();
	}
}

短信廣播接受者

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.smsreceiver.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>
        <receiver android:name="com.itheima.smsreceiver.SmsReceiver">
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
          <!-- 配置廣播接受者 -->
        <receiver android:name="com.itheima.smsreceiver.OutCallReceiver">
            <intent-filter android:priority="1000">
                <!-- 配置廣播接收者關心的事件是外撥電話 -->
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
package com.itheima.smsreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

/**
 * 1.創建一個收音機 繼承廣播接受者
 *
 */
public class OutCallReceiver extends BroadcastReceiver {
	//當接收到消息對應的方法
	@Override
	public void onReceive(Context context, Intent intent) {
		String number = getResultData();
		if("5556".equals(number)){
			setResultData(null);
		}
	}
}
package com.itheima.smsreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		System.out.println("短信到來了。 。。。");
		Object[] objs = (Object[]) intent.getExtras().get("pdus");
		for (Object obj : objs) {
			// 得到短信對象
			SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
			String body = smsMessage.getMessageBody();
			String sender = smsMessage.getOriginatingAddress();
			System.out.println("body:" + body);
			System.out.println("sender:" + sender);
			// 終止掉當前的廣播。
			if ("5556".equals(sender)) {
				abortBroadcast();
			}
		}
	}

}

自定義廣播的發送和接受

發送廣播的電臺

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.sender.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>
package com.itheima.sender;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	/**
	 * 發送廣播事件 (消息)
	 * @param view
	 */
	public void click(View view){
		Intent intent = new Intent();
		//自定義一個廣播動作。
		intent.setAction("com.itheima.sender.jiuminga");
		//大吼一聲 把消息發出去了。 無序廣播
		sendBroadcast(intent);
		//發送有序廣播
		//sendOrderedBroadcast(intent, receiverPermission);
	}
}

警察

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:theme="@android:style/Theme.Translucent"
            android:name="com.itheima.police.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>
        <receiver android:name="com.itheima.police.PoliceReceiver">
            <intent-filter >
                <action android:name="com.itheima.sender.jiuminga"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
package com.itheima.police;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class PoliceReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "我是警察,我收到了消息", 1).show();
	}

}

廣播接受者的優先級

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

    <Button
        android:onClick="send1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="發送無序廣播" />

    <Button
        android:onClick="send2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="發送有序廣播" />
    
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.broadcasttest"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.broadcasttest.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>

        <receiver android:name="com.itheima.broadcasttest.Level1Receiver" >
            <intent-filter android:priority="1000" >
                <action android:name="com.itheima.broadcasttest.songwennuan" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.itheima.broadcasttest.Level2Receiver" >
            <intent-filter android:priority="500" >
                <action android:name="com.itheima.broadcasttest.songwennuan" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.itheima.broadcasttest.Level3Receiver" >
            <intent-filter android:priority="100" >
                <action android:name="com.itheima.broadcasttest.songwennuan" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.itheima.broadcasttest.FinalReceiver" >
            <intent-filter android:priority="0" >
                <action android:name="com.itheima.broadcasttest.songwennuan" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
package com.itheima.broadcasttest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	/**
	 * 發送無序廣播
	 * @param view
	 */
	public void send1(View view){
		Intent intent = new Intent();
		intent.setAction("com.itheima.broadcasttest.songwennuan");
		intent.putExtra("msg", "發1萬塊");
		//無序廣播,不可被攔截,不可終止。
		sendBroadcast(intent);
	}
	/**
	 * 發送有序廣播
	 * @param view
	 */
	public void send2(View view){
		Intent intent = new Intent();
		intent.setAction("com.itheima.broadcasttest.songwennuan");
		//有序廣播,可被攔截,可終止,可以修改數據。
		sendOrderedBroadcast(intent, null, new FinalReceiver(), null, 0, "給農民兄弟發10000塊錢", null);
	}
}
package com.itheima.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class Level1Receiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String message = getResultData();
		System.out.println("省級部門得到中央的消息:"+message);
		abortBroadcast();
		setResultData("給農民兄弟發5000塊錢");
	}

}
package com.itheima.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class Level2Receiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String message = getResultData();
		System.out.println("市級部門得到省級的消息:"+message);
		setResultData("給農民兄弟發2000塊錢");

	}

}
package com.itheima.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class Level3Receiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String message = getResultData();
		System.out.println("鄉級部門得到市的消息:"+message);
		setResultData("給農民兄弟發兩大大米");

	}

}
package com.itheima.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class FinalReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String message = getResultData();
		System.out.println("農民兄弟得到鄉的消息:"+message);
	}

}

進程的優先級&爲什麼使用服務

服務: 長期後臺運行的沒有界面的組件

android應用:什麼地方需要用到服務?

 

天氣預報:後臺的連接服務器的邏輯,每隔一段時間 獲取最新的天氣信息

股票顯示:後臺的連接服務器的邏輯,每隔一段時間 獲取最新的股票信息

mp3播放器: 後臺長期的播放音樂。

 

new Thread(){}.start(); 子線程沒有界面,也是長期後臺運行的。

 

android系統進程管理是按照一定的規則的:

1.應用程序一旦被打開 通常情況下關閉(清空任務棧)後進程不會停止。方面下一次快速啓動。

帶來內存不足的問題。

2.Android系統有一套 內存清理機制。 按照優先級去回收系統的內存。

 

 

進程分爲5個等級的優先級:(從高到低)

 

1.Foreground process 前臺進程  用戶正在玩的應用程序對應的進程

 

2.Visible process 可視進程 用戶仍然可以看到這個進程的界面。

 

3.Service process服務進程  應用程序有一個服務組件在後臺運行。

 

4.Background process 後臺進程  應用程序沒有服務在運行 並且最小化 (activity onstop

 

5.Empty process 空進程 沒有任何運行的activity, 任務棧空了

 

長期後臺運行的組件, 不要在activity開啓子線程。

應該是創建服務,在服務裏面開啓子線程。

 

服務的目的:

1.長期後臺運行。

2.提高進程的優先級,系統不容易回收掉進程,即便回收了,內存充足的時候,把進程重新創建。

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.testservice.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>
        <service android:name="com.itheima.testservice.MyService"></service>
    </application>

</manifest>
<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"
    tools:context=".MainActivity" >

    <Button
        android:onClick="click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="開啓服務" />

</RelativeLayout>
package com.itheima.testservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {

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

	//oncreate ondestory onstart onstop onresume onpause
	//服務沒有界面 
	@Override
	public void onCreate() {
		System.out.println("服務創建了");
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println("服務接收到了開啓指令");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("服務銷燬了");
		super.onDestroy();
	}
}
package com.itheima.testservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

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

	public void click(View view){
		Intent intent = new Intent(this,MyService.class);
		startService(intent);
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章