m_shige1979のときどきITブログ

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

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

https://github.com/mshige1979

androidでBroadcastReceiverの簡易サンプル

これなに?

インテントと言われるものを配信して、自分のアプリや他のアプリで検知できるようにするらしい
これでアクティビティを起動したり他のアプリの値を受け取れたりするとのこと

必要なこと

アクティビティとは別にブロードキャストレシーバーを作成することになります。

実装

画面

f:id:m_shige1979:20150123054236p:plain
※適当に

Actibity
package jp.mshige1979.app.sampleappbroatcast1;

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){
                Intent intent = new Intent("jp.mshige1979.app.sampleappbroatcast1.test1");
                sendBroadcast(intent);
            }
        });
    }


    @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);
    }
}
BroadcastReceiver
package jp.mshige1979.app.sampleappbroatcast1;

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

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast toast = Toast.makeText(context, "sample", Toast.LENGTH_SHORT);
        toast.show();
    }
}
マニフェスト編集
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.mshige1979.app.sampleappbroatcast1" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".MyReceiver"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="jp.mshige1979.app.sampleappbroatcast1.test1"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

送信する方法

                Intent intent = new Intent("jp.mshige1979.app.sampleappbroatcast1.test1");
                sendBroadcast(intent);

インテントに名前を指定して識別する必要があるとのこと
※今回はパッケージ名と適当なサンプル文字列を指定

受信する場合はマニフェストに追加する

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="jp.mshige1979.app.sampleappbroatcast1.test1"/>
            </intent-filter>
        </receiver>

android studioではある程度は自動で用意してくれますが、「intent-filter」などは別途追加する必要があります

結果

f:id:m_shige1979:20150123055510g:plain

所感

ブログを書く最近ネタがなくなってきたw
急いで学習している部分もあるせいだけどブログに書くだけでは学習することにならないので一度止めて
アプリ開発などをしたほうがいいかも
キリがいいところまでやってからブログを書くのは止めるかも…