SuperbookKing

10.消息传递之Intent

Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents.

Intent 一次对即将执行的操作的抽象描述

1 Action 之 打电话发短信

(注意添加打电话发短信权限

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />


Button callbutton = (Button) findViewById(R.id.callbutton);
Button smsbutton = (Button) findViewById(R.id.smsbutton);

case R.id.callbutton:

intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:5554"));
startActivity(intent);
System.out.println("H=HHUhu回话vcalllll");
break;
case R.id.smsbutton:
intent.setAction(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:5554"));
intent.putExtra("sms_body", "n enol I!!");
startActivity(intent);
System.out.println("H=HHUhu回话vcalllll");
break;

2 Action 之 Activity跳转

Button redirbutton = (Button) findViewById(R.id.redirbutton);

case R.id.redirbutton:
intent.setClass(DemoAndroidActivity.this, SecondAndroidActivity.class);
intent.putExtra("title", "呜呼哀哉!!");
startActivityForResult(intent, REQUEST_CODE);
System.out.println("跳转");
break;

(// 返回时的回调方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.i(TAG, "MainActivity-->onActivityResult");
if(REQUEST_CODE == requestCode)
{
if(SecondAndroidActivity.RESULT_CODE == resultCode)
{
Toast.makeText(this, data.getExtras().getString("back"), Toast.LENGTH_LONG).show();
}
}
}

3 Action 之 Service跳转

(1)

case R.id.onStartService:
intent.setClass(DemoAndroidActivity.this, ExampleSercice.class);
startService(intent);
break;
case R.id.onStopService:
intent.setClass(DemoAndroidActivity.this, ExampleSercice.class);
stopService(intent);
break;

(2)

protected void unbindService()
{
Log.i(TAG, "MainActivity-->unbindService");
if (isConnected)
{
unbindService(conn);

}
}

protected void bindService()
{
Log.i(TAG, "MainActivity-->bindService");
Intent intent =new Intent(DemoAndroidActivity.this,BinderSercice.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}

Action 之 Broadcast跳转

intent.setAction(ACTION);
intent.putExtra("number", ((EditText) findViewById(R.id.edtxtBroadcast)).getText().toString());
SharedPreferences pres= DemoAndroidActivity.this.getSharedPreferences("wsc",Context.MODE_PRIVATE);
Editor editor = pres.edit();
editor.putInt("number", 123456);
editor.commit();
Log.i(TAG, "broadcast:"+Thread.currentThread().getId());
sendBroadcast(intent);

注:Context.sendBroadcast(), Context.sendOrderedBroadcast(), Context.sendStickyBroadcast()传送给 broadcast receivers

posted on 2012-07-29 21:46  SuperbookKing  阅读(182)  评论(0)    收藏  举报