알림 예제(Notification Example)

 버튼 누르면 toast 메시지가 뜨고 진동과 함께 상태창에 알림이 온다.

상태창의 알림을 터치하면 SubActivity가 호출된다.


activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.notificationexample.mystoryg.notificationexample.MainActivity">

<Button
android:id="@+id/notification"
android:text="notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>


MainActivity.java

 package com.notificationexample.mystoryg.notificationexample;


import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button noti = (Button) findViewById(R.id.notification);
noti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showToast();
showNotification();
}
});
}

private void showToast() {
Toast toast = Toast.makeText(this, "알림을 확인해주세요!", Toast.LENGTH_LONG);
toast.show();
}

private void showNotification() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, SubActivity.class)

.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("알림").setContentText("터치해주세요.").setTicker("확인해주세요.")

.setSmallIcon(R.drawable.email).setContentIntent(pendingIntent).setAutoCancel(true)

.setWhen(System.currentTimeMillis()).setDefaults(Notification.DEFAULT_ALL);

nm.notify(1, builder.getNotification());
}
}


activity_sub.xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_sub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.notificationexample.mystoryg.notificationexample.SubActivity">

<TextView
android:text="확인하셨습니다."
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Button
android:id="@+id/home"
android:text="처음으로"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


SubActivity.java

 package com.notificationexample.mystoryg.notificationexample;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SubActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);

Button home = (Button)findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
}



'프로그래밍 > Android' 카테고리의 다른 글

Preference Example  (0) 2017.01.10
알람 예제 (AlarmManager Example)  (0) 2016.12.22
브로드캐스트 리시버 (BroadcastReceiver Example)  (0) 2016.12.20
Service Example  (0) 2016.12.17
명시적 인텐트(Explicit Intent)  (0) 2016.12.16
암시적 인텐트(Implicit Intent)  (0) 2016.12.15
WebView 줄바꿈 문제  (0) 2016.02.18

Service Example

 background daemon 방식의 서비스 예제이다. 웹 서핑과 음악 감상을 동시에 하는 앱을 만들고자 한다면 백그라운드 서비스를 통해 음악을 재생하면 된다.


 하기 예제는 서비스를 실행하면 핸들러에 의해서 1초 단위로 run() 함수가 실행된다. 마지막 run() 호출 후 1초 이내에 서비스를 종료하면 onDestroy()가 호출되어 mIsRunning이 false가 된다. 서비스를 manifest에 추가해주는 것도 잊지말자.


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.serviceexmaple.mystoryg.serviceexample">

<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
</application>

</manifest> 


activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.serviceexmaple.mystoryg.serviceexample.MainActivity">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<Button
android:id="@+id/start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" />

<Button
android:id="@+id/stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service" />
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/view_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>


MainActivity.java

 package com.serviceexmaple.mystoryg.serviceexample;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();

ComponentName mServiceName;
TextView mTextView;
// Intent mIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mTextView = (TextView) findViewById(R.id.view_service);

Button start = (Button) findViewById(R.id.start_service);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSrv();
}
});

Button stop = (Button) findViewById(R.id.stop_service);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopSrv();
}
});
}


private void startSrv() {
// mIntent = new Intent(this, MyService.class);
// mServiceName = startService(mIntent);
mServiceName = startService(new Intent(this, MyService.class));
Log.d(TAG, "mServiceName = " + mServiceName.toString());
mTextView.append("Service Start.\n");
}

private void stopSrv() {
if (null == mServiceName) {
mTextView.append("Service is not start.\n");
return;
}
Intent intent = new Intent();
intent.setComponent(mServiceName);
// if(stopService(mIntent)) {
if (stopService(intent)) {
mTextView.append("Service Stop.\n");
} else {
mTextView.append("Service is already stop.\n");
}
}
}


MyService.class

package com.serviceexmaple.mystoryg.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service implements Runnable {
public static final String TAG = MyService.class.getSimpleName();
private int mStartId;
private Handler mHandler;
private boolean mIsRunning;

public MyService() {
}

@Override
public void onCreate() {
Log.i(TAG, "onCreate()");
super.onCreate();

mIsRunning = false;
mHandler = new Handler();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "startId = " + startId);
mStartId = startId;
if (!mIsRunning) {
mHandler.postDelayed(this, 1000);
mIsRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
Log.i(TAG, "onDestroy()");
mIsRunning = false;
super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void run() {
if (!mIsRunning) {
Log.i(TAG, "It run after call onDestroy()");
} else {
Log.i(TAG, "run()");
mHandler.postDelayed(this, 1000);
}
}

} 


실행 결과 log

12-17 17:24:34.700 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN

12-17 17:24:34.789 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP

12-17 17:24:34.794 11136-11136/com.serviceexmaple.mystoryg.serviceexample D/MainActivity: mServiceName = ComponentInfo{com.serviceexmaple.mystoryg.serviceexample/com.serviceexmaple.mystoryg.serviceexample.MyService}

12-17 17:24:34.795 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: onCreate()

12-17 17:24:34.807 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: startId = 1

12-17 17:24:35.810 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:36.812 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:37.814 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:38.816 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:39.819 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:40.345 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN

12-17 17:24:40.453 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP

12-17 17:24:40.459 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: onDestroy()

12-17 17:24:40.820 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: It run after call onDestroy() 


명시적 인텐트(Explicit Intent)


 실행할 컴포넌트 이름을 명시적으로 정하는 방식이다.


 MainActivity(caller)의 intent를 기반으로 framework에 SubActivity(callee)의 실행을 요청하여 해당 액티비티를 실행한다. call 버튼에 의한 것이면 startActivity()로 결과를 받아올 수 없다.


 call_result 버튼에 의한 것이면 startActivityForResult()로 결과를 받아올 수 있다. 그에 대한 처리는 onActivityResult()에서 한다.


activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.explicitintent.mystoryg.explicitintent.MainActivity">

<Button
android:id="@+id/call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call activity" />

<Button
android:id="@+id/call_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call activity and get result" />

<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="return data" />
</LinearLayout>


MainActivity.java

 package com.explicitintent.mystoryg.explicitintent;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener {

private static final String TAG = MainActivity.class.getSimpleName();
public static final String INPUT = "input";
public static final String RESULT = "result";
private static final int SUB_ACTIVITY = 1;
TextView mResult;

static final int[] BUTTONS = {
R.id.call,
R.id.call_result
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResult = (TextView) findViewById(R.id.result);
for (int button : BUTTONS) {
Button btn = (Button) findViewById(button);
btn.setOnClickListener(this);
}
}

@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.call:
call();
break;
case R.id.call_result:
call_result();
break;
}
}

private void call() {
Intent intent = new Intent(getApplicationContext(), SubActivity.class);
intent.putExtra(INPUT, "This is normal call.");
mResult.setText("return data");
startActivity(intent);
}

private void call_result() {
Intent intent = new Intent(getApplicationContext(), SubActivity.class);
intent.putExtra(INPUT, "This is call and get result.");
mResult.setText("return data");
startActivityForResult(intent, SUB_ACTIVITY);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SUB_ACTIVITY) {
if (resultCode == RESULT_OK) {
mResult.setText(data.getStringExtra(RESULT));
} else {
mResult.setText("Error!");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}


activity_sub.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_sub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.explicitintent.mystoryg.explicitintent.SubActivity">

<EditText
android:id="@+id/result_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Button
android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="response" />

</LinearLayout> 


SubActivity.java

package com.explicitintent.mystoryg.explicitintent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SubActivity extends Activity {

private static final String TAG = SubActivity.class.getSimpleName();
EditText mEdit;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);

String input = getIntent().getStringExtra(MainActivity.INPUT);
if (null != input) {
mEdit = (EditText) findViewById(R.id.result_message);
mEdit.setText(input);
}

Button response = (Button) findViewById(R.id.response);
response.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String response = mEdit.getText().toString();
if(response.length() != 0) {
Intent intent = new Intent();
intent.putExtra(MainActivity.RESULT, response);
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED);
}

finish();
}
});
}

} 



+ Recent posts