Android

안드로이드 스튜디오 도움되는 정보들 1

 

  1. Android – myLooper() vs getMainLooper()
  2. how to use postDelayed() correctly in android studio?
  3. How to use the SwipeRefreshLayout?
  4. Android sample bluetooth code to send a simple string via bluetooth
  5. How to add dividers and spaces between items in RecyclerView?
  6. Adding button action in custom notification
  7. Downloading a website to a string
  8. Android Handler Tutorial
  9. start activity with left to right mode
  10. material design FAB speed dial menu tutorial (Code with Joyce)

 

 


 

Android – myLooper() vs getMainLooper()

 

getMainLooper() – Returns the application’s main looper, which lives in the main thread of the application.

myLooper() – Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.

 

 

new Handler(Looper.getMainLooper()).post(new Runnable() {
// execute code that must be run on UI thread
});

 

 

https://stackoverflow.com/questions/34322498/android-mylooper-vs-getmainlooper

 


 

how to use postDelayed() correctly in android studio?

 

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Log.d("Handler", "Running Handler");
    }
}, 1000);

 

 

https://stackoverflow.com/questions/42379301/how-to-use-postdelayed-correctly-in-android-studio

 

 

 


 

How to use the SwipeRefreshLayout?

 

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

 

SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE);
mSwipeRefreshLayout.setOnRefreshListener(() -> {
    mSwipeRefreshLayout.setRefreshing(false);
});

 

https://stackoverflow.com/questions/23014846/how-to-use-the-swiperefreshlayout

https://developer.android.com/training/swipe/add-swipe-interface

 

 


 

Android sample bluetooth code to send a simple string via bluetooth

 

 

 

https://stackoverflow.com/questions/22899475/android-sample-bluetooth-code-to-send-a-simple-string-via-bluetooth

 

 

 


 

How to add dividers and spaces between items in RecyclerView?

 

mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

 

https://stackoverflow.com/questions/24618829/how-to-add-dividers-and-spaces-between-items-in-recyclerview

 

 


 

Adding button action in custom notification

 

private void startNotification(){
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(ns);

    Notification notification = new Notification(R.drawable.ic_launcher, null,
            System.currentTimeMillis());

    RemoteViews notificationView = new RemoteViews(getPackageName(),
            R.layout.mynotification);

    //the intent that is started when the notification is clicked (works)
    Intent notificationIntent = new Intent(this, FlashLight.class);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    notification.contentView = notificationView;
    notification.contentIntent = pendingNotificationIntent;
    notification.flags |= Notification.FLAG_NO_CLEAR;

    //this is the intent that is supposed to be called when the 
    //button is clicked
    Intent switchIntent = new Intent(this, switchButtonListener.class);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0,
            switchIntent, 0);

    notificationView.setOnClickPendingIntent(R.id.closeOnFlash,
            pendingSwitchIntent);

    notificationManager.notify(1, notification);
}


public static class switchButtonListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("Here", "I am here");
        FlashOnOff flashLight;
        flashLight = new FlashOnOff();
        flashLight.flashLightOff();
        flashLight.releaseCamera();
    }
}

 

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="100" >

    <ImageView
        android:id="@+id/notifiation_image"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="30"
        android:contentDescription="@string/appImage"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/appName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        android:gravity="center"
        android:text="@string/flashLightOn"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/closeOnFlash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="20"
        android:text="@string/close" />
</LinearLayout>

 

 

<receiver android:name="FlashLight$switchButtonListener" />

 

 

https://stackoverflow.com/questions/21925688/adding-button-action-in-custom-notification

 


 

7. Downloading a website to a string

 

try 
{
    URL url = new URL("http://yourwebpage.com");
    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) 
    {
     // str is one line of text; readLine() strips the newline character(s)
     // You can use the contain method here.
       if(str.contains(editText.getText().toString))
        {
          You can perform your logic here!!!!!         
        }
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

 

 

https://stackoverflow.com/questions/11590899/downloading-a-website-to-a-string

 

 


 

Android Handler Tutorial

 

핸들러는 백그라운드 쓰레드에서 UI 쓰레드와의 소통을 가능하게한다.
새 핸들러 인스턴스를 만들면 하나의 쓰레드와 그 쓰레드의 메시지 큐와 바인딩 된다.

 

 

 

public class MainActivity extends AppCompatActivity {
    ProgressBar progressBar;
    Button startProgress,stopProgress;
    TextView textView;
    int MAX = 100;
    Handler mHandlerThread;
    private static final int START_PROGRESS = 100;
    private static final int UPDATE_COUNT = 101;
    Thread thread1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        startProgress = (Button) findViewById(R.id.start_progress);
        textView = (TextView) findViewById(R.id.textView);
        progressBar.setMax(MAX);

        thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int  i = 0;i<100;i++){
                    Log.d("I",":"+i);
                    progressBar.setProgress(i);
                    try{
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException ex){
                        ex.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = UPDATE_COUNT;
                    message.arg1 = i;
                    mHandlerThread.sendMessage(message);
                }
            }
        });


        startProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentProgess = progressBar.getProgress();
                /*Message message = new Message();
                message.what = START_PROGRESS;*/
                mHandlerThread.sendEmptyMessage(START_PROGRESS);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandlerThread = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == START_PROGRESS){
                    thread1.start();
                }
                else if(msg.what == UPDATE_COUNT){
                    textView.setText("Count"+msg.arg1);
                }
            }
        };
    }
}

 

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.manish.developer.threadapplication.MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/start_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/progressBar"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="62dp"
        android:text="Start" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/start_progress"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="85dp"
        android:layout_marginRight="85dp"
        android:textSize="16sp"
        android:text="Count 1"
        android:layout_alignTop="@+id/start_progress" />

</RelativeLayout>

 

https://medium.com/@manishgiri/android-handler-tutorial-ccda6994f01c

 

 


 

9. start activity with left to right mode

 

https://stackoverflow.com/questions/16648279/start-activity-with-left-to-right-mode

 

I’ll try to help you with the following example:

res/anim/trans_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
<translate 
        android:fromXDelta="100%p" 
        android:toXDelta="0" 
        android:duration="@android:integer/config_longAnimTime"/>
</set>

res/anim/trans_left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
         android:fromXDelta="0" 
         android:toXDelta="-100%p" 
         android:duration="@android:integer/config_longAnimTime"/>
</set>

res/anim/trans_right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate 
        android:fromXDelta="-100%p" 
        android:toXDelta="0" 
        android:duration="@android:integer/config_longAnimTime"/>
</set>

res/anim/trans_right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
         android:fromXDelta="0" 
         android:toXDelta="100%p" 
         android:duration="@android:integer/config_longAnimTime"/>
</set>

src/Activity2

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traces);
        overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
...}

@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.trans_right_in, R.anim.trans_right_out);
}

 


 

material design FAB speed dial menu tutorial (Code with Joyce)

 

material design FAB로 메뉴 만들기/ FAB speed dial menu tutorial / floating action button tutorial (Code with Joyce)
https://www.youtube.com/watch?v=ircI_ABl2XE

 

https://material.io/components/buttons-floating-action-button#types-of-transitions

 

Related posts

Leave a Comment