Android notification的简单实践

通知处理,也就是大家都熟悉的通知,比如说某某的下载已经结束,会提示下载结束等等

这样的实现,其实很简单。

1.首先要有一个线程,可是说是下载的线程(大部分人都把这个变成服务来做)

2.在线程开始的时候打出警告就ok了

下面我们就简单的实装一个

public class MainActivity extends Activity implements View.OnClickListener{

	private static final int NOTE_ID = 100;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Button button = new Button(this);
		button.setText("Post New Notification");
		button.setOnClickListener(this);
		setContentView(button);
	}

	@Override
	public void onClick(View v) {
        handler.postDelayed(task, 10000);
        Toast.makeText(this, "Notification will post in 10 seconds", Toast.LENGTH_SHORT).show();
	}

	private Handler handler = new Handler();

	private Runnable task = new Runnable(){

		@Override
		public void run() {
			NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
			Intent launchIntent = new Intent(getApplicationContext(),MainActivity.class);
			PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);
			Notification note = new Notification(R.drawable.ic_launcher,"Something Happened",System.currentTimeMillis());
			note.setLatestEventInfo(getApplicationContext(), "Finished", "Click Here", contentIntent);
			note.defaults |= Notification.DEFAULT_SOUND;
			note.flags |= Notification.FLAG_AUTO_CANCEL;
			
			manager.notify(NOTE_ID, note);
		}
	};
}

 上面的Activity是没有layout的,就是把button加入到界面。

代码 我不想解释什么,我想既然看到我博客的人,应该会明白到底去哪才能看到类的说明。

上面就是简简单单的时候了notification的功能。不过基本上用不了,因为在实际应用的时候,基本上都是拿服务的形式来做的。

下面我在做一个比较复杂的程序。

package com.java.chenhailong.notifyactivityman;

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

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button startButton = (Button) findViewById(R.id.button1);
		Button stopButton = (Button) findViewById(R.id.button2);

		startButton.setOnClickListener(startListener);
		stopButton.setOnClickListener(stopListener);
	}

	private OnClickListener startListener = new OnClickListener() {
		public void onClick(View v) {
			startService(new Intent(MainActivity.this,
					NotificationChangeService.class));
		}
	};

	private OnClickListener stopListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			stopService(new Intent(MainActivity.this,
					NotificationChangeService.class));
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

  

package com.java.chenhailong.notifyactivityman;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.ConditionVariable;
import android.os.IBinder;

public class NotificationChangeService extends Service {

	private NotificationManager mNotificationManager;
	private ConditionVariable mCondition;

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

	public void onCreate() {
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// サービスはメインスレッドで実行されるため、処理を止めないように更新処理を別スレッドに。
		Thread thread = new Thread(null, mTask, "NotifyingService");
		mCondition = new ConditionVariable(false);
		thread.start();
	}

	private int WAIT_TIME = 5000;// 5秒単位
	private Runnable mTask = new Runnable() {
		public void run() {
			for (int i = 0; i < 4; ++i) {
				showNotification(R.drawable.mini_circle, "丸を表示しています");
				if (mCondition.block(WAIT_TIME))
					break;
				showNotification(R.drawable.mini_rect, "三角を表示しています");
				if (mCondition.block(WAIT_TIME))
					break;
				showNotification(R.drawable.ruler_triangle, "音符を表示しています");
				if (mCondition.block(WAIT_TIME))
					break;
			}
			// アニメーションの終了、サービスを終了する
			NotificationChangeService.this.stopSelf();
		}
	};

	// ユニークなIDを取得するために、R.layout.mainのリソースIDを使います
	private static int NOTIFICATION_ID = R.layout.activity_main;

	private void showNotification(int drawableId, CharSequence text) {

		// 通知内容を決定
		Notification notification = new Notification(drawableId, null,
				System.currentTimeMillis());

		// PendingIntentはタイミングを指定したインテント
		// 今回はユーザーがnotificationを選択した時にActivityを起動
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MainActivity.class), 0);

		// notificationを設定
		notification.setLatestEventInfo(this, "NotificationService", text,
				contentIntent);

		mNotificationManager.notify(NOTIFICATION_ID, notification);
	}

	@Override
	public void onDestroy() {
		// サービスの停止時、通知内容を破棄する
		mNotificationManager.cancel(NOTIFICATION_ID);
		// スレッドを停止するため、ブロックを解除
		mCondition.open();
	}
}
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java.chenhailong.notifyactivityman.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="NotificationChangeService"></service>

 其他的文件我就不拷了,大家只要知道思想,我想会做出更加漂亮的程序来,我这个也就是个例子。

程序我也提供给大家,大家也可以实践一下。来看看Android的奇妙之处

猜你喜欢

转载自chenhailong.iteye.com/blog/1882508