当前位置: 代码迷 >> Android >> Android之BroadcastReceiver基准用法
  详细解决方案

Android之BroadcastReceiver基准用法

热度:72   发布时间:2016-04-28 01:16:28.0
Android之BroadcastReceiver标准用法


BrocastReceiver用法:

1、继承BroadcastReceiver类

2、重写onReceive函数(见最下面代码)

3、在Mainfest文件中注册receiver

<!-- 自定义BrocastReceiver -->

<receiver android:name=".MyBroadcastReceiver">

     <intent-filter >

          <action android:name="android.action.MyEx"/>

          <category android:name="android.intent.category.DEFAULT"/>

     </intent-filter>

</receiver>

4、在Activity中启用BrocastReceiver

    private TextView mybu;

    private MyBroadcastReceiver myBroadcastReceiver;   

    publicstaticfinal String ACTION1 = "android.action.MyEx";

    publicstaticfinal String EXTRA1 = "extra";

 

    @Override

    protectedvoidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

       

        mybu = (TextView) findViewById(R.id.mybu);

       myBroadcastReceiver = new MyBroadcastReceiver();

    }

   

    publicvoid mybuClick(View v)

    {

        Intent intent = newIntent(ACTION1);

        intent.putExtra(EXTRA1, "welldone");

        sendBroadcast(intent);

    }

注意:

一、在XML文件中使用onClick代替OnClickListener

<TextView

        android:id="@+id/mybu"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world"

        android:onClick="mybuClick"

        android:clickable="true"

        />

二、Notification的使用:

publicclass MyBroadcastReceiver extends BroadcastReceiver{

    @Override

    publicvoidonReceive(Context context, Intent intent) {

        String data = intent.getExtras().getString(MainActivity.EXTRA1);

       //获得NotificationManager

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);       

        //此方法已被废弃

//      Notification notification = new Notification(R.drawable.icon3,"提醒",System.currentTimeMillis());

        Notification.Builder builder = new Builder(context);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,

                new Intent(context,MainActivity.class) , 0);

        builder.setSmallIcon(R.drawable.icon3)

               .setWhen(System.currentTimeMillis())

               .setContentTitle("通知")

               .setContentText(data)

               .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)

               .setContentIntent(pendingIntent);

        manager.notify(3, builder.build());

        //builder.getNotification();方法也被废弃了,注意使用build()方法

    } 

}


  相关解决方案