2013年12月23日月曜日

USB Host に挑戦

アンドロイドのドキュメント:USB Host

USBディバイスはMbed を使いました。

参考サイト:kshoji:自作のUSBデバイスを、Androidで動かす

参考サイトに詳細に解説されています。

参考サイトの一部必要な所だけ取り出してみました。

とりあえず、Mbed に送信してLED4を点灯させてみる。
点灯と消灯の二つのボタンを置いて操作する。
USBディバイスを接続した時に使うアプリを聞いてくる。

回路図:アンドロイドとUSBホストケーブルで接続する
Mbed のソースコード:参考サイトのソースコードをそのまま使いました。
#include "mbed.h"
#include "USBHID.h"

// device
USBHID hid;

// read
HID_REPORT recv;
BusOut leds(LED1, LED2, LED3, LED4);

// write
HID_REPORT send;
AnalogIn input(p15);

int main(void)
{
    int lastData = 0;
    int currentData;

    send.length = 64;
    while (1) {
        // read
        hid.readNB(&recv);
        if (recv.length > 0) {
            leds = recv.data[0];
            
        }

        currentData = input.read_u16();
        if (currentData != lastData) {
            lastData = currentData;

            // write
            send.data[0] = (currentData >> 8) & 0xff;
            send.data[1] = currentData & 0xff;
            //hid.send(&send);
        }
        
    }
}

アンドロイドアプリのソースコード
エラー処理や例外・終了処理は考慮していない。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hidtest002"
    android:installLocation="preferExternal"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="12"
        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.example.hidtest002.MainActivity"
            android:label="@string/app_name" >

            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>

            <meta-data
                android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>

res/xml/device_filter.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Interface class: USB HID -->
    <usb-device class="3" subclass="0" protocol="0" />
</resources>

MainActivity.java
package com.example.hidtest002;

import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

 private static final String TAG = "HidTest";
 private TextView text;
 private UsbDeviceConnection deviceConnection = null;
 private UsbEndpoint outputEndpoint2;

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

  text = (TextView) findViewById(R.id.textView1);

  //  ボタンがクリックされた時の処理
  Button btn1 = (Button) findViewById(R.id.button1);
  btn1.setOnClickListener(this);
  Button btn2 = (Button) findViewById(R.id.button2);
  btn2.setOnClickListener(this);

  //  USB ディバイスが接続されていない時は終了
  if (!UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(getIntent().getAction())) {
   finish();
  } else {
   // USB ディバイスを接続
   Intent intent = getIntent();
   UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
   if (device != null) {
    Log.v(TAG, "UsbDevice がある");
    UsbInterface usbInterface = findUsbInterface(device);
    if (usbInterface != null) {
     // アタッチ
     UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
     deviceConnection = usbManager.openDevice(device);
     deviceConnection.claimInterface(usbInterface, true);
    }
   }
  }

 }

 /*
  * UsbInterface の確認 
  */
 private UsbInterface findUsbInterface(UsbDevice device) {
  // TODO 自動生成されたメソッド・スタブ
  text.setText("UsbDevice.getDeviceName():" + device.getDeviceName() + "\n");
  int count = device.getInterfaceCount();// 4
  text.append("UsbDevice.getInterfaceCount():" + count + "\n");
  for (int i = 0; i < count; i++) {
   UsbInterface usbInterface = device.getInterface(i);

   UsbEndpoint inputEndpoint = null;
   UsbEndpoint outputEndpoint = null;

   text.append("**************************" + "\n");
   text.append(" UsbInterface.getEndpointCount():" + usbInterface.getEndpointCount() + "\n");
   if (usbInterface.getEndpointCount() >= 1) {
    for (int endpointIndex = 0; endpointIndex < usbInterface.getEndpointCount(); endpointIndex++) {
     UsbEndpoint endpoint = usbInterface.getEndpoint(endpointIndex);
     text.append(endpointIndex + ":");

     if ((endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK || endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) {
      if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
       outputEndpoint = outputEndpoint == null ? endpoint : outputEndpoint;
       outputEndpoint2 = endpoint;
       text.append("  UsbEndpoint:getDirection()" + endpoint.getDirection() + "\n");// USB_DIR_OUT
      }
     }
    }

    if (inputEndpoint != null || outputEndpoint != null) {
     return usbInterface;
    }
   }
  }

  return null;
 }

 /*
  * ボタンが押された時の処理
  */
 @Override
 public void onClick(View v) {
  // TODO 自動生成されたメソッド・スタブ
  byte data1 = 0;
  byte data2 = 0;
  byte data3 = 0;
  byte data4 = 0;

  switch (v.getId()) {
  case R.id.button1:
   Log.i("buttonTest", "点灯ボタンが押された");
   data1 = 0;
   data2 = 0;
   data3 = 0;
   data4 = (byte) 8;
   break;
  case R.id.button2:
   Log.i("buttonTest", "消灯ボタンが押された");
   data1 = 0;
   data2 = 0;
   data3 = 0;
   data4 = 0;
   break;

  }
  outPutMbed(new byte[] { (byte) (data1 | data2 | data3 | data4) });

 }

 // Mbed に送信
 private void outPutMbed(byte[] bytes) {
  // TODO 自動生成されたメソッド・スタブ
  final int maxPacketSize = outputEndpoint2.getMaxPacketSize();
  for (int i = 0; i < bytes.length; i += maxPacketSize) {
   byte[] writeBuffer = new byte[maxPacketSize];
   int length = (bytes.length - i) < writeBuffer.length ? bytes.length - i : writeBuffer.length;
   System.arraycopy(bytes, i, writeBuffer, 0, length);
   deviceConnection.bulkTransfer(outputEndpoint2, writeBuffer, writeBuffer.length, 0);
  }
 }

 /*
  * メニューの処理
  */
 @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;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
  case R.id.itemFinish:
   Log.v(TAG, "finish");
   finish();
   return true;
  }

  return false;
 }
}

activity_main.xml
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="点灯" />

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="消灯" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/hello_world" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


2013年10月6日日曜日

IntentService を使ってみる:android

http://developer.android.com/guide/components/services.html で紹介されているソースコードを実行してみる。
サービスの終了操作を気にしないでいいようです。
5秒後にサービス終了するコード。

package com.example.intentservice;

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

public class MainActivity extends Activity {

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

  Intent intent = new Intent(this, HelloIntentService.class);
  startService(intent);
 }
}

package com.example.intentservice;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class HelloIntentService extends IntentService {

 private static final String TAG = "HelloIntentService";

 /** 
  * A constructor is required, and must call the super IntentService(String)
  * constructor with a name for the worker thread.
  */
 public HelloIntentService() {
  super("HelloIntentService");

  Log.v(TAG, "HelloIntentService");
 }

 /**
  * The IntentService calls this method from the default worker thread with
  * the intent that started the service. When this method returns, IntentService
  * stops the service, as appropriate.
  */
 @Override
 protected void onHandleIntent(Intent intent) {
  Log.v(TAG, "onHandleIntent");

  // Normally we would do some work here, like download a file.
  // For our sample, we just sleep for 5 seconds.
  long endTime = System.currentTimeMillis() + 5 * 1000;
  while (System.currentTimeMillis() < endTime) {
   synchronized (this) {
    try {
     wait(endTime - System.currentTimeMillis());
    } catch (Exception e) {
    }
   }
  }
  Log.v(TAG, "onHandleIntent 終了");
 }

 @Override
 public void onDestroy() {
  Log.v(TAG, "onDestroy");
 }

}


UIの変更を考えてみる
package com.example.intentservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.widget.TextView;

public class MainActivity extends Activity {

 public static class SampleHandler extends Handler {
  private MainActivity con;

  public SampleHandler(MainActivity mainActivity) {
   // TODO 自動生成されたコンストラクター・スタブ
   this.con = mainActivity;
  }

  @Override
  public void handleMessage(Message msg) {
   Bundle bundle = msg.getData();
   
    TextView textView = (TextView) con.findViewById(R.id.textView1);
    textView.setText( bundle.getString("mystring") );
  }
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  SampleHandler handler = new SampleHandler(this);

  Intent intent = new Intent(this, HelloIntentService.class);
  intent.putExtra("messenger", new Messenger(handler));
  startService(intent);
 }
}

package com.example.intentservice;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class HelloIntentService extends IntentService {

 private static final String TAG = "HelloIntentService";

 public HelloIntentService() {
  super("HelloIntentService");

  Log.v(TAG, "HelloIntentService");
 }

 @Override
 protected void onHandleIntent(Intent intent) {
  Log.v(TAG, "onHandleIntent");

  Bundle bundle = intent.getExtras();
  if (bundle != null) {
   Messenger messenger = (Messenger) bundle.get("messenger");
   Message msg = Message.obtain();
   
   Bundle data = new Bundle();
   data.putString("mystring", "Hello!");
   msg.setData(data);
   try {
    messenger.send(msg);
   } catch (RemoteException e) {
    Log.i("error", "error");
   }
  }
 }

 @Override
 public void onDestroy() {
  Log.v(TAG, "onDestroy");
 }

}

while ループが永遠に終わらない処理の場合、
呼び出し元のアクティビティーが終了しても、動き続けるので、
IntentServiceを終了させる処理が必要なようです。


package com.example.intentservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.widget.TextView;

public class MainActivity extends Activity {

 public static class SampleHandler extends Handler {
  private MainActivity con;

  public SampleHandler(MainActivity mainActivity) {
   // TODO 自動生成されたコンストラクター・スタブ
   this.con = mainActivity;
  }

  @Override
  public void handleMessage(Message msg) {
   Bundle bundle = msg.getData();

   TextView textView = (TextView) con.findViewById(R.id.textView1);
   textView.setText(bundle.getString("mystring"));
  }
 }

 private SampleHandler handler;
 private Intent intent;

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

  handler = new SampleHandler(this);

  intent = new Intent(this, HelloIntentService.class);
  intent.putExtra("messenger", new Messenger(handler));
  startService(intent);
 }

 @Override
 public void onDestroy() {
  super.onDestroy();
  // The service is no longer used and is being destroyed

  if (intent != null) {
   stopService(intent);
   intent = null;
  }
 }
}
package com.example.intentservice;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class HelloIntentService extends IntentService {

 private static final String TAG = "HelloIntentService";
 private boolean loopFlag = true;

 public HelloIntentService() {
  super("HelloIntentService");

  Log.v(TAG, "HelloIntentService");

 }

 @Override
 protected void onHandleIntent(Intent intent) {
  Log.v(TAG, "onHandleIntent");

  Bundle bundle = intent.getExtras();

  while (loopFlag) {
   synchronized (this) {
    try {
     Log.v(TAG, "HelloIntentService");
     GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
     String stringTime = gc.get(Calendar.HOUR_OF_DAY) + ":" + gc.get(Calendar.MINUTE) + ":" + gc.get(Calendar.SECOND);

     if (bundle != null) {
      Messenger messenger = (Messenger) bundle.get("messenger");
      Message msg = Message.obtain();

      Bundle data = new Bundle();

      data.putString("mystring", stringTime);
      msg.setData(data);
      try {
       messenger.send(msg);
      } catch (RemoteException e) {
       Log.i("error", "error");
      }
     }

     wait(1000);
    } catch (Exception e) {
    }
   }
  }

 }

 @Override
 public void onDestroy() {
  Log.v(TAG, "onDestroy");
  loopFlag = false;
 }

}

2013年10月5日土曜日

Service と BroadcastReceiver :android



Activity で レシーバーを登録して、インテントでサービスを開始する。

サービスでは、システムの時間を取得して、レシーバーに送る。

レシーバーでは受っとった時間を画面に表示する。

package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
 IntentFilter intentFilter;
 MyService4Receiver receiver;
 Intent intent = null;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  // レシーバーの登録
  receiver = new MyService4Receiver();
  receiver.activity = this;
  intentFilter = new IntentFilter();
  intentFilter.addAction(MyService4Service.actionName);
  registerReceiver(receiver, intentFilter);
 }
 
 public void onResume() {
  super.onResume();
  Log.i("タグ", "onResume()");

  intent = new Intent(getBaseContext(), MyService4Service.class);
  startService(intent);
 }
 
 public void onDestroy() {
  super.onDestroy();
  Log.i("タグ", "onDestroy()");
  
  unregisterReceiver(receiver);//レシーバー登録解除
  
  if (intent != null)
  {
   stopService(intent);//サービスの停止
  }
  intent = null;

 }

}

package com.example.servicetest;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class MyService4Service extends Service {
 public static final String actionName = "MYSERVICE4_ACTION";
 MyHandler mHandler = null;
 private static Context contex;

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.i("MyService4Service", "onStartCommand");

  if (mHandler == null)
  {
   mHandler = new MyHandler();
   mHandler.sendEmptyMessage(1);
  }
  
  contex = getBaseContext();

  return START_NOT_STICKY;//サービスの強制終了後、再起動しない
 }

 public void onDestroy()
 {
  if (mHandler != null)
  {
   mHandler.removeMessages(1);
   mHandler = null;
  }
  super.onDestroy();
 }

 @Override
 public IBinder onBind(Intent arg0) {
  // TODO 自動生成されたメソッド・スタブ
  return null;
 }

 static class MyHandler extends Handler
 {
  public void handleMessage(Message msg)
  {
   GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
   String stringTime = gc.get(Calendar.HOUR_OF_DAY) + ":" + gc.get(Calendar.MINUTE) + ":" + gc.get(Calendar.SECOND);

   Intent broadcastIntent = new Intent();
   broadcastIntent.putExtra("message", stringTime);
   broadcastIntent.setAction(actionName);
   contex.sendBroadcast(broadcastIntent);

   sendEmptyMessageDelayed(1, 1000);
  }
 }
}
package com.example.servicetest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MyService4Receiver extends BroadcastReceiver {
 MainActivity activity;// onCreate の receiver.activity = this;


 @Override
 public void onReceive(Context context, Intent intent) {
  // メッセージを取ってくる
  
  Log.i("MyService4Receiver", "onReceive");
  
  Bundle bundle = intent.getExtras();
  String message = bundle.getString("message");
  // そいつを表示する
  if (activity != null)
  {
   TextView tv = (TextView) activity.findViewById(R.id.textView1);
   tv.setText(message);
  }
 }
}

サービスはマニフェストにも登録しておく、
レシーバはregisterReceiver();で動的に登録してあるので、マニフェストには登録しなくても動く。

2013年10月4日金曜日

サービスのバインドについて考えてみる


サービスをバインドして、サービスからUIを変更
package com.example.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

import com.example.bindservice.SampleService.LocalBinder;

public class MainActivity extends Activity {

 private static final String TAB = "MainActivity";
 private TextView tv;

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

  tv = (TextView) findViewById(R.id.textView1);

 }

 @Override
 public void onStart() {
  Log.i(TAB, "onStart");
  super.onStart();
  // Bind
  Intent intent = new Intent(getApplicationContext(), SampleService.class);
  bindService(intent, mySrviceConnection, Context.BIND_AUTO_CREATE);//サービスをバインド
 }

 @Override
 public void onStop() {
  Log.i(TAB, "onStop");
  super.onStop();
  // Unbind
  unbindService(mySrviceConnection);//サービスをアンバインド
 }

 private ServiceConnection mySrviceConnection = new ServiceConnection() {

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   // TODO 自動生成されたメソッド・スタブ
   LocalBinder binder = (SampleService.LocalBinder) service;
   binder.getService(tv);
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO 自動生成されたメソッド・スタブ

  }
 };

}
package com.example.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class SampleService extends Service {

 private static final String TAB = "SampleService";
 private IBinder mBinder = new LocalBinder();

 public class LocalBinder extends Binder {
        SampleService getService(TextView tv) {
      Log.i(TAB, "LocalBinder");//
      tv.setText("サービスから変更");
            return SampleService.this;
        }
    }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO 自動生成されたメソッド・スタブ
  Log.i(TAB, "onBind");//起動時に呼ばれる

  return mBinder;
 }

 @Override
 public void onDestroy() {
  Log.i(TAB, "onDestroy");
 }
}

ボタンクリックでUIを変更してみる
package com.example.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.bindservice.SampleService.LocalBinder;

public class MainActivity extends Activity {

 private static final String TAB = "MainActivity";
 private TextView tv;
 private LocalBinder binder;

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

  tv = (TextView) findViewById(R.id.textView1);

  Button button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Log.i(TAB, "ボタン2が押された");
    if (binder != null){
     Log.i(TAB, "binder は null で無い");
     binder.getService(tv);
    }else{
     Log.i(TAB, "binder は null");
    }
   }
  });
 }

 @Override
 public void onStart() {
  Log.i(TAB, "onStart");
  super.onStart();
  // Bind
  Intent intent = new Intent(getApplicationContext(), SampleService.class);
  bindService(intent, mySrviceConnection, Context.BIND_AUTO_CREATE);//サービスをバインド
 }

 @Override
 public void onStop() {
  Log.i(TAB, "onStop");
  super.onStop();
  // Unbind
  unbindService(mySrviceConnection);//サービスをアンバインド
 }

 private ServiceConnection mySrviceConnection = new ServiceConnection() {

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   // TODO 自動生成されたメソッド・スタブ
   binder = (SampleService.LocalBinder) service;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO 自動生成されたメソッド・スタブ

  }
 };

}
package com.example.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class SampleService extends Service {

 private static final String TAB = "SampleService";
 private IBinder mBinder = new LocalBinder();

 public class LocalBinder extends Binder {
  void getService(TextView tv) {
   Log.i(TAB, "LocalBinder");//
   tv.setText("サービスから変更");
  }
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO 自動生成されたメソッド・スタブ
  Log.i(TAB, "onBind");//起動時に呼ばれる

  return mBinder;
 }

 @Override
 public void onDestroy() {
  Log.i(TAB, "onDestroy");
 }
}


サービスでスレッドを利用して定期的にUIを更新
package com.example.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.bindservice.SampleService.LocalBinder;

public class MainActivity extends Activity {

 private static final String TAB = "MainActivity";
 private TextView tv;
 private LocalBinder binder;

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

  tv = (TextView) findViewById(R.id.textView1);

  Button button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Log.i(TAB, "ボタン2が押された");
    if (binder != null){
     Log.i(TAB, "binder は null ではない");
     binder.getService(tv);
    }else{
     Log.i(TAB, "binder は null");
    }
   }
  });
 }

 @Override
 public void onStart() {
  Log.i(TAB, "onStart");
  super.onStart();
  // Bind
  Intent intent = new Intent(getApplicationContext(), SampleService.class);
  bindService(intent, mySrviceConnection, Context.BIND_AUTO_CREATE);//サービスをバインド
 }

 @Override
 public void onStop() {
  Log.i(TAB, "onStop");
  super.onStop();
  // Unbind
  unbindService(mySrviceConnection);//サービスをアンバインド
 }

 private ServiceConnection mySrviceConnection = new ServiceConnection() {

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   // TODO 自動生成されたメソッド・スタブ
   binder = (SampleService.LocalBinder) service;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO 自動生成されたメソッド・スタブ

  }
 };

}
package com.example.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class SampleService extends Service {

 private Handler handler;

 public class MyThread implements Runnable {

  private int data;

  @Override
  public void run() {
   // TODO 自動生成されたメソッド・スタブ
   while (true) {
    Log.i(TAB, "run::" + data);//二番目に呼ばれる

    data++;
    Message msg = handler.obtainMessage();
    msg.arg1 = data;
    handler.sendMessage(msg);
    try {
     Thread.sleep(2000);
    } catch (InterruptedException e) {
     // TODO 自動生成された catch ブロック
     e.printStackTrace();
    }
   }
  }

 }

 private static final String TAB = "SampleService";
 private IBinder mBinder = new LocalBinder();

 public class LocalBinder extends Binder {

  void getService(final TextView tv) {
   Log.i(TAB, "LocalBinder");//
   //tv.setText("setData から変更");//ここでも変更可能

   new Thread(new MyThread()).start();

   /*
   //動くがメモリーリークの可能性がある
   //This Handler class should be static or leaks might occur
   handler = new Handler() {
    public void handleMessage(Message msg) {
     //updata.update(tv, data);
     Log.i(TAB, "handleMessage::" + msg);

     tv.setText(String.valueOf(msg.arg1));//ここでも変更可能

    }
   };
   */
   handler = new MyHandler(tv);
  }
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO 自動生成されたメソッド・スタブ
  Log.i(TAB, "onBind");//起動時に呼ばれる

  return mBinder;
 }

 @Override
 public void onDestroy() {
  Log.i(TAB, "onDestroy");
 }

 public static class MyHandler extends Handler {
  private TextView tv;

  public MyHandler(TextView tv) {
   // TODO 自動生成されたコンストラクター・スタブ
   this.tv = tv;
  }

  @Override
  public void handleMessage(Message msg) {
   Log.i(TAB, "handleMessage::" + msg);
   tv.setText(String.valueOf(msg.arg1));//ここでも変更可能
  }

 }
}

サービスで変更された値をアクティビティに戻してUIを変更する。
package com.example.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.bindservice.SampleService.LocalBinder;
import com.example.bindservice.SampleService.UpdateData;

public class MainActivity extends Activity {

 private static final String TAB = "MainActivity";
 private TextView tv;
 private LocalBinder binder;

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

  tv = (TextView) findViewById(R.id.textView1);

  Button button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Log.i(TAB, "ボタン2が押された");
    if (binder != null) {
     Log.i(TAB, "binder は null ではない");
     binder.getService(new UpdateData() {

      @Override
      public void update(int data) {
       // TODO 自動生成されたメソッド・スタブ
       tv.setText(data + "");
      }
     });

    } else {
     Log.i(TAB, "binder は null");
    }
   }
  });
 }

 @Override
 public void onStart() {
  Log.i(TAB, "onStart");
  super.onStart();
  // Bind
  Intent intent = new Intent(getApplicationContext(), SampleService.class);
  bindService(intent, mySrviceConnection, Context.BIND_AUTO_CREATE);//サービスをバインド
 }

 @Override
 public void onStop() {
  Log.i(TAB, "onStop");
  super.onStop();
  // Unbind
  unbindService(mySrviceConnection);//サービスをアンバインド
 }

 private ServiceConnection mySrviceConnection = new ServiceConnection() {

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   // TODO 自動生成されたメソッド・スタブ
   binder = (SampleService.LocalBinder) service;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO 自動生成されたメソッド・スタブ

  }
 };

}
package com.example.bindservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class SampleService extends Service {

 public interface UpdateData {
  public void update(int data);
 }

 private Handler handler;

 public class MyThread implements Runnable {

  private int data;

  @Override
  public void run() {
   // TODO 自動生成されたメソッド・スタブ
   while (true) {
    Log.i(TAB, "run::" + data);//二番目に呼ばれる

    data++;
    Message msg = handler.obtainMessage();
    msg.arg1 = data;
    handler.sendMessage(msg);
    try {
     Thread.sleep(2000);
    } catch (InterruptedException e) {
     // TODO 自動生成された catch ブロック
     e.printStackTrace();
    }
   }
  }

 }

 private static final String TAB = "SampleService";
 private IBinder mBinder = new LocalBinder();

 public class LocalBinder extends Binder {

  void getService(UpdateData updata) {
   Log.i(TAB, "LocalBinder");//
   //tv.setText("setData から変更");//ここでも変更可能

   new Thread(new MyThread()).start();

   handler = new MyHandler(updata);
  }
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO 自動生成されたメソッド・スタブ
  Log.i(TAB, "onBind");//起動時に呼ばれる

  return mBinder;
 }

 @Override
 public void onDestroy() {
  Log.i(TAB, "onDestroy");
 }

 public static class MyHandler extends Handler {
  private UpdateData updata;

  public MyHandler(UpdateData updata) {
   // TODO 自動生成されたコンストラクター・スタブ
   //this.tv = tv;
   this.updata = updata;
  }

  @Override
  public void handleMessage(Message msg) {
   Log.i(TAB, "handleMessage::" + msg);
   //tv.setText(String.valueOf(msg.arg1));//ここでも変更可能
   updata.update(msg.arg1);
  }

 }
}

時間を表示してみる。
package com.example.bindservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.bindservice.SampleService.LocalBinder;
import com.example.bindservice.SampleService.UpdateData;

public class MainActivity extends Activity {

 private static final String TAB = "MainActivity";
 private TextView tv;
 private LocalBinder binder;

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

  tv = (TextView) findViewById(R.id.textView1);

  Button button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Log.i(TAB, "ボタン2が押された");
    if (binder != null) {
     Log.i(TAB, "binder は null ではない");
     binder.getService(new UpdateData() {

      @Override
      public void update(String data) {
       // TODO 自動生成されたメソッド・スタブ
       tv.setText(data + "");
      }
     });

    } else {
     Log.i(TAB, "binder は null");
    }
   }
  });
 }

 @Override
 public void onStart() {
  Log.i(TAB, "onStart");
  super.onStart();
  // Bind
  Intent intent = new Intent(getApplicationContext(), SampleService.class);
  bindService(intent, mySrviceConnection, Context.BIND_AUTO_CREATE);//サービスをバインド
 }

 @Override
 public void onStop() {
  Log.i(TAB, "onStop");
  super.onStop();
  // Unbind
  unbindService(mySrviceConnection);//サービスをアンバインド
 }

 private ServiceConnection mySrviceConnection = new ServiceConnection() {

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   // TODO 自動生成されたメソッド・スタブ
   binder = (SampleService.LocalBinder) service;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO 自動生成されたメソッド・スタブ

  }
 };

}
package com.example.bindservice;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class SampleService extends Service {

 public interface UpdateData {
  public void update(String data);
 }

 private static final String TAB = "SampleService";
 private IBinder mBinder = new LocalBinder();

 public class LocalBinder extends Binder {

  void getService(UpdateData updata) {
   Log.i(TAB, "LocalBinder");//
   //tv.setText("setData から変更");//ここでも変更可能

   //new Thread(new MyThread()).start();

   MyHandler handler = new MyHandler(updata);
   handler.sendEmptyMessage(1);
  }
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO 自動生成されたメソッド・スタブ
  Log.i(TAB, "onBind");//起動時に呼ばれる

  return mBinder;
 }

 @Override
 public void onDestroy() {
  Log.i(TAB, "onDestroy");
 }

 public static class MyHandler extends Handler {
  private UpdateData updata;

  public MyHandler(UpdateData updata) {
   // TODO 自動生成されたコンストラクター・スタブ
   //this.tv = tv;
   this.updata = updata;
  }

  @Override
  public void handleMessage(Message msg) {
   Log.i(TAB, "handleMessage::" + msg);

   GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
   String data = gc.get(Calendar.HOUR_OF_DAY) + ":" + gc.get(Calendar.MINUTE) + ":" + gc.get(Calendar.SECOND);

   sendEmptyMessageDelayed(1, 1000);
   
   updata.update(data);
  }

 }
}




2013年9月24日火曜日

キャッチされなかった例外が発生した場合の処理:Android UncaughtExceptionHandler


キャッチされなかった例外が発生した場合、アプリを再起動させる。

package com.example.exceptionchach;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

 protected static final String TAG = "123";

 private MainActivity activityMain;

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

  activityMain = this;

  //キャッチされない例外により、スレッドが突然終了したときや、  
  //このスレッドに対してほかにハンドラが定義されていないときに  
  //呼び出されるデフォルトのハンドラを設定します。  
  Thread.setDefaultUncaughtExceptionHandler(new CsUncaughtExceptionHandler(activityMain));

  findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // 例外を発生させる
    throw new IllegalStateException();
   }
  });
 }

 @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.example.exceptionchach;

import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Intent;
import android.util.Log;

public class CsUncaughtExceptionHandler implements UncaughtExceptionHandler {

 private static final String TAG = "CsUncaughtExceptionHandler";

 // 現在設定されている UncaughtExceptionHandler を退避
 final UncaughtExceptionHandler savedUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();

 private MainActivity myContext;

 public CsUncaughtExceptionHandler(MainActivity context) {
  // TODO 自動生成されたコンストラクター・スタブ
  myContext = context;
 }

 /*
  * キャッチされない例外によって指定されたスレッドが終了したときに呼び出されます 
  */
 @Override
 public void uncaughtException(Thread thread, Throwable exception) {
  // TODO 自動生成されたメソッド・スタブ
  Log.d(TAG, "uncaughtException");

  // catchされなかった例外処理 エラーログを保存したりする。

  // 退避しておいた UncaughtExceptionHandler を実行
  //savedUncaughtExceptionHandler.uncaughtException(thread, ex);//例外のダイアログ表示

  //再起動処理
  Intent in = new Intent(myContext, MainActivity.class);
  myContext.startActivity(in);

  myContext.finish();
  android.os.Process.killProcess(android.os.Process.myPid());

 }

}