Mutual calls between Android components

Source: Internet
Author: User

We study two questions,
1. How the service changes a textview of activity through broadcaster.
(Study this problem, considering that the service returns MSG to the activity after it has received the message from the server side.)

2. How the activity invokes a service through binder.
(Study this problem, consider the action of interacting with server side, package to service,activity only render interface, call service method)

The structure diagram is shown below:

As follows:

Click the "Start Service" button to start the service and then change the activity's UI.

Click the "Send msg to Server" button to invoke the service method to display the Notificationbar

Code

MyService's:

Package com.bankcomm.test;

Import android.app.Notification;
Import Android.app.NotificationManager;
Import android.app.PendingIntent;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import Android.graphics.Color;
Import Android.os.Binder;
Import Android.os.IBinder;

public class MyService extends Service {
Private Notificationmanager Notificationmanager = null;
Private final IBinder binder = new Localbinder ();

@Override
public void OnCreate () {
Sendmsgtoactivity ("Service is oncreating.\n");
}
@Override
Public IBinder Onbind (Intent Intent) {
TODO auto-generated Method Stub
String msg = "Activity is sendding message to service,\n service send msg to server!\n";
Sendmsgtoactivity (msg);
return binder;
}
private void Sendmsgtoactivity (String msg) {
Intent Intent = new Intent ("com.android.Hou.msg");
Intent.putextra ("msg", MSG);
This.sendbroadcast (Intent);

}
@Override
public void OnDestroy () {
TODO auto-generated Method Stub
Super.ondestroy ();

if (notificationmanager!= null) {
Notificationmanager.cancel (0);
notificationmanager= null;

}
}
private void Shownotification (String msg) {
Notificationmanager = (Notificationmanager) getsystemservice (Context.notification_service);
Defining various properties of the notification
Notification Notification =new Notification (R.drawable.ic_launcher,
"A Message coming!", System.currenttimemillis ());
Flag_auto_cancel This notification can be cleared by the purge button of the status bar
Flag_no_clear the notification cannot be cleared by the Purge button in the status bar
Flag_ongoing_event notifications are placed in the running
Whether the flag_insistent is always on, such as music always playing, know user response
Notification.flags |= notification.flag_ongoing_event; Place this notification in the "ongoing" or "running" Group of the notification bar
Notification.flags |= notification.flag_no_clear; Indicates that this notification is not cleared and is often used with flag_ongoing_event when you click Clear Notification in the notification bar
Notification.flags |= notification.flag_show_lights;
Default_all use all default values, such as sound, vibration, splash screen, etc.
Default_lights using default Flash Hints
Default_sounds using default cue Sound
Default_vibrate Use default phone shake, add <uses-permission android:name= "Android.permission.VIBRATE"/> Permissions
Notification.defaults = notification.default_lights;
Overlay Effect Constants
notification.defaults=notification.default_lights| Notification.default_sound;
Notification.ledargb = Color.Blue;
NOTIFICATION.LEDONMS = 5000; Flash time, milliseconds

Set event messages for notifications
Intent notificationintent =new Intent (Mainactivity.this, Mainactivity.class); Activity to jump after clicking on the notification
Intent notificationintent = new Intent (Getapplicationcontext (), mainactivity.class); The load class, if directly through the class name, will reload the page when clicked, unable to restore the last page state.
Notificationintent.setflags (Intent.flag_activity_single_top);
Pendingintent contentitent = pendingintent.getactivity (this, 0, notificationintent, 0);
Notification.setlatesteventinfo (This, "message", "message:" + MSG, contentitent);

Pass the notification to Notificationmanager.
Notificationmanager.notify (0, notification);

}
/**
* Get information from activity
*/
public void Receivermsgtoactivity (String msg) {
Sendmsgtoactivity ("\ n receivermsgtoactivity:" +msg);
}
public void Sendmsgtoserver (String msg) {
Shownotification (msg);
}
public class Localbinder extends binder{
Public MyService GetService () {
return myservice.this;
}
}

}

Mainactivity's:

Package com.bankcomm.test;

Import java.util.List;

Import android.app.Activity;
Import Android.app.ActivityManager;
Import Android.content.BroadcastReceiver;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
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.TextView;

public class Mainactivity extends Activity implements Onclicklistener {
Private TextView txtmsg;
Private String msg = "";
Private Updatereceiver receiver;
Private MyService MyService;
Private final static String TAG = MainActivity.class.getSimpleName ();

@Override
protected void OnCreate (Bundle savedinstancestate) {
TODO auto-generated Method Stub
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Txtmsg = (TextView) Findviewbyid (r.id.txtmsg);
This.findviewbyid (r.id.btnsend). Setonclicklistener (this);
This.findviewbyid (R.id.btnstart). Setonclicklistener (this);

Subscribe to broadcast
Receiver = new Updatereceiver ();
Intentfilter filter = new Intentfilter ();
Filter.addaction ("com.android.Hou.msg");
This.registerreceiver (receiver, filter);

}

public class Updatereceiver extends Broadcastreceiver {
@Override
public void OnReceive (context context, Intent Intent) {
TODO auto-generated Method Stub
Get the information that the service sent over
msg = Intent.getstringextra ("msg");
System.out.println ("msg==============" +msg);
Txtmsg.append (msg);
}

}

Private Serviceconnection conn = new Serviceconnection () {

@Override
public void onservicedisconnected (componentname name) {
TODO auto-generated Method Stub
MyService = null;
}

@Override
public void onserviceconnected (componentname name, IBinder service) {
TODO auto-generated Method Stub
MyService = ((myservice.localbinder) service). GetService ();
LOG.I (TAG, "onserviceconnected myservice:" + myservice);
}
};

@Override
protected void OnDestroy () {
TODO auto-generated Method Stub
Super.ondestroy ();

End Service
if (conn!=null) {
Unbindservice (conn);
Myservice=null;
}
}

@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Intent Intent = new Intent (mainactivity.this, Myservice.class);
int id = V.getid ();
Switch (ID) {
Case R.id.btnstart:
Determine if the service is started
if (false==isservicerunning (this, Myservice.class.getName ())) {

LOG.I (TAG, "Start" + Myservice.class.getSimpleName () + "service");
This.bindservice (Intent, Conn, bind_auto_create);
}
LOG.I (TAG, Myservice.class.getName () + "Run Status:" +isservicerunning (This, Myservice.class.getName ()));
Break
Case R.id.btnsend:
Determine if the service is started
if (false==isservicerunning (this, Myservice.class.getName ())) {
LOG.I (TAG, "Start" +myservice.class.getsimplename () + "service");
Start Service
This.bindservice (Intent, Conn, bind_auto_create);

}
LOG.I (TAG, Myservice.class.getName () + "Run Status:" +isservicerunning (This, Myservice.class.getName ()));
LOG.I (TAG, "OnClick myservice:" +myservice); Null here when starting the service for the first time (the small part thinks that although the service has started successfully, but not all initialized yet)

if (myservice!=null) {
Myservice.sendmsgtoserver ("I am sending msg to server");
Myservice.receivermsgtoactivity ("This is a msg");

}
Break
Default
Break
}

}
/**
* Determine if the service is running
*
* @param context
* @param className Judgment Service Name: Package name + class name
* @return True when running false is not running
*/
public static Boolean isservicerunning (context context, String ClassName) {
Boolean isrunning = false;
Activitymanager Activitymanager = (activitymanager) context
. Getsystemservice (Context.activity_service);
Get all the Services
list<activitymanager.runningserviceinfo> Services = Activitymanager
. getrunningservices (Integer.max_value);
if (services! = null && services.size () > 0) {
for (Activitymanager.runningserviceinfo service:services) {
if (Classname.equals (Service.service.getClassName ())) {
IsRunning = true;
Break
}
}

}
return isrunning;
}

}

Mybroadcastreceiver's:

Package com.bankcomm.test;

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;

public class Mybroadcastreceiver extends Broadcastreceiver {

@Override
public void OnReceive (context context, Intent Intent) {
TODO auto-generated Method Stub
Intent service = new Intent (context,myservice.class);
System.out.println ("broadcastreceiver======");
Context.startservice (service);
}

}

Layout and configuration file information:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:orientation= "Vertical" >

<textview
Android:id= "@+id/txtmsg"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Server"
/>

<button
Android:id= "@+id/btnstart"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Start Service"/>

<button
Android:id= "@+id/btnsend"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Send msg to Server"/>

</LinearLayout>

<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Com.bankcomm.test"
Android:versioncode= "1"
Android:versionname= "1.0" >

<USES-SDK android:minsdkversion= "Ten"/>

<instrumentation
Android:name= "Android.test.InstrumentationTestRunner"
Android:targetpackage= "Com.bankcomm"/>

<application
android:icon= "@drawable/ic_launcher"
Android:label= "@string/app_name" >
<uses-library android:name= "Android.test.runner"/>
<activity
Android:name= "Com.bankcomm.test.MainActivity" >
<intent-filter >
<action android:name= "Android.intent.action.MAIN"/>

<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name= ". MyService "></service>
<receiver android:name= ". Mybroadcastreceiver "></receiver>
</application>

</manifest>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.