现在的位置: 首页 > 综合 > 正文

Android实现程序前后台切换效果

2013年12月06日 ⁄ 综合 ⁄ 共 6915字 ⁄ 字号 评论关闭

本文演示如何在Android中实现程序前后台切换效果。

  

看到:http://www.cnblogs.com/hanyonglu/archive/2012/04/15/2450551.html  

说明这种效果实现。

经过测试,发现上面的方法有不少问题,

1、HOME键是不能用的,不知道原作者是否是在2.3等老版本上做的测试,4.0上Activity中己无法捕获到HOME键了,

2、单纯的在onStop中加入处理,也是不行的,因为只要是Activity被完全覆盖,就会调用onStop, 这样一切Activity,就来了notification,这显然不是我们所要的。

3、加入Service来只处理这样一个问题,这样的消耗也太大了。

经过修改,有了下面的方法。

1、还是在onStop中做NotificationExtend的操作,但在NotificationExtend中判断是否是运行在了后台。

activityManager.getRunningAppProcesses() ==RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE

表示运行在后台。

2、不论是从哪个Activity中发出的Notification请求, 都应是操作的同一个对象,这样才能进行全局控制。

3、在onRestart中可以做cancel notification的操作。同样要有一个标志判断是否有notification目前存在才去做。

修改后代码如下:

public class MainActivity extends Activity {
	private Button btnShow = null;
	public Intent intent = null;
	public static NotificationExtend notification = new NotificationExtend();
	final static String TAG = "XUE";
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// ��������
	// intent = new Intent(MainActivity.this, AppStatusService.class);
//		 startService(intent);
Log.e(TAG,"---Main---onCreate---Activity:" + this.hashCode() + " task:" + getTaskId());
		
		btnShow = (Button) findViewById(R.id.btnShow);
		btnShow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MainActivity.this,
						ShowMessageActivity.class);
				
				startActivity(i);
			}
		});
	}
	
	

	// ���HOME��ʱ��������̨����
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// ����HOME��
		Log.e(TAG,"---onKeyDown---");
		
		if (keyCode == KeyEvent.KEYCODE_HOME) {
			// ��ʾNotification
		// AppManager.context = this;
			// moveTaskToBack(true);

			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getRepeatCount() == 0) {
			Log.e(TAG,"---KEY---BACK---");
			// ֹͣ����
   //         if(intent != null)
//			   stopService(intent);
			
			finish();

			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onAttachedToWindow() {
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
		super.onAttachedToWindow();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		
		
		super.onDestroy();
//		stopService(intent);
		Log.e(TAG,"---Main---onDestroy---Activity:" + this.hashCode() + " task:" + getTaskId());
		
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
	
		notification.setActivity(this);	
		notification.showNotification();
		super.onStop();
		Log.e(TAG,"---Main---onStop---Activity:" + this.hashCode() + " task:" + getTaskId());
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.e(TAG,"---Main---onResume---Activity:" + this.hashCode() + " task:" + getTaskId());

	}



	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		notification.cancelNotification();
		Log.e(TAG,"---Main---onRestart---Activity:" + this.hashCode() + " task:" + getTaskId());
	}
}

public class ShowMessageActivity extends Activity{
	private Button btnExit = null;
	private NotificationExtend notification = null;
	private final String TAG = "XUE";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showmessage_activity);
		Log.e(TAG,"---Show--onCreate----Activity:" + this.hashCode() + " task:" + getTaskId());
		btnExit = (Button)findViewById(R.id.button1);
        notification = MainActivity.notification;
        	
		btnExit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// ����HOME��
    	if(keyCode == KeyEvent.KEYCODE_HOME){
    		// ��ʾNotification
    	//	notification = new NotificationExtend(this);
    		notification.showNotification();
    		
    		moveTaskToBack(true);
    	
    		return true;
    	}
    	
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
    	
			notification.setActivity(this);
    		notification.showNotification();
    		Log.e(TAG,"---Show--onStop----Activity:" + this.hashCode() + " task:" + getTaskId());
		super.onStop();
	}

	@Override
    public void onAttachedToWindow () {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
        super.onAttachedToWindow();
    }
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		notification.cancelNotification();
		Log.e(TAG,"---Show---onRestart---Activity:" + this.hashCode() + " task:" + getTaskId());
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e(TAG,"---Show---onResume---Activity:" + this.hashCode() + " task:" + getTaskId());
	}
}

 

public class NotificationExtend {
	private Activity context;
	private final String TAG = "XUE";
	private boolean flag = false;  

	public NotificationExtend() {
		
	}
	
	public void setActivity(Activity context){
		this.context = context;
	}

    public void showNotification()
    {
       if (!isAppOnBackground()) { 
          Log.e("XUE","---XUE---Foreground---");
       } else { 
          Log.e("XUE","---XUE---Background---");
          showNotification_rl();
       }
    }
	
	// ��ʾNotification
	public void showNotification_rl() {

        // ����һ��NotificationManager������
        NotificationManager notificationManager = (
        		NotificationManager)context.getSystemService(
        				android.content.Context.NOTIFICATION_SERVICE);
        
        Log.e("XUE", "");
        // ����Notification�ĸ�������
        Notification notification = new Notification(
        		R.drawable.icon,"TEST", 
        		System.currentTimeMillis());
        // ����֪ͨ�ŵ�֪ͨ����"Ongoing"��"��������"����
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
      
//        notification.flags |= Notification.FLAG_NO_CLEAR; 
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
  //      notification.defaults = Notification.DEFAULT_LIGHTS;
  //      notification.ledARGB = Color.BLUE;
  //      notification.ledOnMS = 5000;
                
      
        CharSequence contentTitle = "TEST Title"; // ֪ͨ������
        CharSequence contentText = "TEST Text"; // ֪ͨ������
        
        Intent notificationIntent = new Intent(context,context.getClass());
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent contentIntent = PendingIntent.getActivity(
        		context, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        
        notification.setLatestEventInfo(
        		context, contentTitle, contentText, contentIntent);
        // ��Notification���ݸ�NotificationManager
        notificationManager.notify(TAG, 5, notification);
        flag = true;

    }
	
	// ȡ��֪ͨ
	public void cancelNotification(){
		if(flag)
		{
		NotificationManager notificationManager = (
				NotificationManager) context.getSystemService(
						android.content.Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(TAG, 5);
		flag = false;
		}
	}


    public boolean isAppOnBackground() { 
    	ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
        // Returns a list of application processes that are running on the device 
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); 
        String packageName = context.getPackageName(); 
        if (appProcesses == null || packageName == null) return false; 
        
        for (RunningAppProcessInfo appProcess : appProcesses) { 
            // The name of the process that this object is associated with. 
        	Log.e("XUE","---isAppOnForeground------" + appProcess.processName + "  packageName:" + packageName);
            if (appProcess.processName.equals(packageName) 
                    && ((appProcess.importance == RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE))) { 
                return true; 
            } 
        } 
        
        return false; 
    }
}

【上篇】
【下篇】

抱歉!评论已关闭.