Skip to content

Instantly share code, notes, and snippets.

@woshidan
Created January 11, 2016 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woshidan/3d31d3de6fc7ab8a9599 to your computer and use it in GitHub Desktop.
Save woshidan/3d31d3de6fc7ab8a9599 to your computer and use it in GitHub Desktop.
LocalBroadCastReciverとIntentServiceで通知
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.woshidan.localbroadcastreceivertest.ListActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_list" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
package com.example.woshidan.localbroadcastreceivertest;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p/>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class AddDataService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
public static final String ACTION_ADD_DATA = "com.example.woshidan.localbroadcastreceivertest.action.ADD_DATA";
public AddDataService() {
super("AddDataService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
Log.d("AddDataService", action);
if (ACTION_ADD_DATA.equals(action)) {
handleActionAddData();
}
}
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionAddData() {
try {
Thread.sleep(10000);
} catch (Exception e) {
Log.e("handleActionAddData", e.toString());
}
List<Item> additionalData;
additionalData = Arrays.asList(new Item("additional1"), new Item("additional2"), new Item("additional3"));
Parcelable[] sendingData = new Parcelable[additionalData.size()];
sendingData = additionalData.toArray(sendingData);
ArrayList<Parcelable> addedItems = new ArrayList<Parcelable>();
for (Item data : additionalData) {
Bundle bundle = new Bundle();
addedItems.add(data);
Parcelable[] sendData = new Parcelable[addedItems.size()];
sendData = addedItems.toArray(sendData);
Intent intent = new Intent();
intent.putExtra(ListActivity.ADDED_ITEM_TITLE, data.getTitle());
intent.putExtra(ListActivity.ADDED_ITEM_LIST, sendData);
intent.putExtra(ListActivity.ADDING_ITEM_LIST, sendingData);
Log.d("AddDataService", data.getTitle());
intent.setAction(ListActivity.ACTION_ADD_DATA);
LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(intent);
try {
Thread.sleep(2000);
} catch (Exception e) {
Log.e("handleActionFoo", e.toString());
}
}
Intent intent = new Intent();
intent.setAction(ListActivity.ACTION_COMPLETE_ADD_DATA);
LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(intent);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.woshidan.localbroadcastreceivertest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ListActivity"
android:label="@string/title_activity_list"
android:theme="@style/AppTheme.NoActionBar" />
<service
android:name=".AddDataService"
android:exported="false"></service>
</application>
</manifest>
package com.example.woshidan.localbroadcastreceivertest;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by woshidan on 2016/01/08.
*/
public class Item implements Parcelable {
private String title;
private int dir_id;
public Item(String title) {
this.title = title;
}
private Item(Parcel in) {
title = in.readString();
dir_id = in.readInt();
}
public static final Creator<Item> CREATOR = new Creator<Item>() {
@Override
public Item createFromParcel(Parcel in) {
return new Item(in);
}
@Override
public Item[] newArray(int size) {
return new Item[size];
}
};
public int getDirId() {
return dir_id;
}
public void setDirId(int id) {
this.dir_id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(title);
out.writeInt(dir_id);
}
}
package com.example.woshidan.localbroadcastreceivertest;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by woshidan on 2016/01/08.
*/
public class ItemViewAdapter extends RecyclerView.Adapter<ItemViewAdapter.ViewHolder> {
private Context mContext;
private ArrayList<Item> items;
public ItemViewAdapter(Context context, ArrayList<Item> items) {
this.mContext = context;
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_view, parent, false));
}
public void onBindViewHolder(ViewHolder holder, int position) {
// データ表示
if (items != null && items.size() > position && items.get(position) != null) {
holder.textView.setText(items.get(position).getTitle());
}
}
@Override
public int getItemCount() {
if (items != null) {
return items.size();
} else {
return 0;
}
}
// ViewHolder(固有ならインナークラスでOK)
class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_view_text);
}
}
}
package com.example.woshidan.localbroadcastreceivertest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListActivity extends AppCompatActivity {
public static String ADDED_ITEM_TITLE = "com.example.woshidan.localbroadcastreceivertest.ADDED_ITEM_TITLE";
public static String ADDED_ITEM_LIST = "com.example.woshidan.localbroadcastreceivertest.ADDED_ITEM_LIST";
public static String ADDING_ITEM_LIST = "com.example.woshidan.localbroadcastreceivertest.ADDING_ITEM_LIST";
public static String ACTION_ADD_DATA = "com.example.woshidan.localbroadcastreceivertest.ACTION_ADD_DATA";
public static String ACTION_COMPLETE_ADD_DATA = "com.example.woshidan.localbroadcastreceivertest.ACTION_COMPLETE_ADD_DATA";
public static String DIR_ID_KEY = "DIR_ID_KEY";
public RecyclerView recyclerView;
public ArrayList<Item> items;
private LocalBroadcastManager localBroadcastManager;
private NoticeProgressReceiver noticeProgressReceiver;
private NoticeCompleteReceiver noticeCompleteReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
recyclerView = (RecyclerView) findViewById(R.id.recyclierView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
items = new ArrayList<Item>();
items.add(new Item("test"));
items.add(new Item("example"));
items.add(new Item("sweet"));
ItemViewAdapter adapter = new ItemViewAdapter(this, items);
recyclerView.setAdapter(adapter);
}
@Override
public onStart() {
super.onStart();
IntentFilter noticeProgressFilter = new IntentFilter();
noticeProgressFilter.addAction(ACTION_ADD_DATA);
noticeProgressReceiver = new NoticeProgressReceiver(this);
localBroadcastManager.registerReceiver(noticeProgressReceiver, noticeProgressFilter);
IntentFilter noticeCompleteFilter = new IntentFilter();
noticeCompleteFilter.addAction(ACTION_COMPLETE_ADD_DATA);
noticeCompleteReceiver = new NoticeCompleteReceiver(this);
localBroadcastManager.registerReceiver(noticeCompleteReceiver, noticeCompleteFilter);
}
@Override
public onStop() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(addedReceiver);
localBroadcastManager.unregisterReceiver(completeReceiver);
}
@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_list, 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_add_items) {
Intent intent = new Intent(this, AddDataService.class);
intent.setAction(AddDataService.ACTION_ADD_DATA);
startService(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void showProgress(int doneCount, int toDoCount, Item addedData) {
Snackbar.make(findViewById(R.id.fab), doneCount + "/" + toDoCount, Snackbar.LENGTH_INDEFINITE).show();
}
}
package com.example.woshidan.localbroadcastreceivertest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.util.Log;
/**
* Created by woshidan on 2016/01/11.
*/
public class NoticeCompleteReceiver extends BroadcastReceiver {
private ListActivity mActivity;
public NoticeCompleteReceiver(ListActivity activity) {
mActivity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Snackbar.make(mActivity.findViewById(R.id.fab), "完了しました", Snackbar.LENGTH_SHORT).show();
}
});
}
}
package com.example.woshidan.localbroadcastreceivertest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.widget.Toast;
/**
* Created by woshidan on 2016/01/11.
*/
public class NoticeProgressReceiver extends BroadcastReceiver {
private ListActivity mActivity;
public NoticeProgressReceiver(ListActivity activity) {
mActivity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
int doneCount = intent.getParcelableArrayExtra(ListActivity.ADDED_ITEM_LIST).length;
int toDoCount = intent.getParcelableArrayExtra(ListActivity.ADDING_ITEM_LIST).length;
final Item item = new Item(intent.getStringExtra(ListActivity.ADDED_ITEM_TITLE));
Snackbar.make(mActivity.findViewById(R.id.fab), doneCount + "/" + toDoCount, Snackbar.LENGTH_INDEFINITE)
.show();
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mActivity.items.add(item);
mActivity.recyclerView.getAdapter().notifyDataSetChanged();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment