m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

androidで通知(Notification)

ステータスバーに通知してなんかを表示させる

裏でサービスが動いていたりアクティビティがメインとなっていない場合に使う

ニュース配信アプリとかのあれ

smartnewとかで新しいニュースが配信されたとかやる場合
あれは別途、他のこともやってそうですけど

実装

画面は適当

f:id:m_shige1979:20150124040822p:plain

Activity
package jp.mshige1979.app.sampleappnotification1;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {

    private Button btn1;

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

        btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Notification n = new Notification(); // Notificationの生成
                n.icon = R.drawable.ic_launcher; // アイコンの設定
                n.tickerText = "This is a notification message..."; // メッセージの設定

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
                n.setLatestEventInfo(getApplicationContext(), "タイトル", "通知されました", pi);

                n.defaults |= Notification.DEFAULT_LIGHTS; // デフォルトLED点滅パターンを設定

                // NotificationManagerのインスタンス取得
                NotificationManager nm =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                nm.notify(1, n); // 設定したNotificationを通知する
            }
        });
    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

f:id:m_shige1979:20150124042032p:plain
f:id:m_shige1979:20150124042039p:plain
f:id:m_shige1979:20150124042046p:plain

終わり